如何使用boto3设置现有S3密钥的Content-Type?
问题描述:
我想使用boto3来更新S3存储桶中现有对象的内容类型,但我该如何做,而不必重新上传文件?如何使用boto3设置现有S3密钥的Content-Type?
file_object = s3.Object(bucket_name, key)
print file_object.content_type
# binary/octet-stream
file_object.content_type = 'application/pdf'
# AttributeError: can't set attribute
有没有一种方法,我已经错过了boto3?
相关的问题:那里似乎
答
不存在任何方法,这boto3,但你可以复制到自己覆盖的文件。
要做到这一点使用过boto3 AWS的低级别的API,这样做:
s3 = boto3.resource('s3')
api_client = s3.meta.client
response = api_client.copy_object(Bucket=bucket_name,
Key=key,
ContentType="application/pdf",
MetadataDirective="REPLACE",
CopySource=bucket_name + "/" + key)
的MetadataDirective="REPLACE"
真可谓是必需的S3覆盖文件,否则你将得到一个错误消息说This copy request is illegal because it is trying to copy an object to itself without changing the object's metadata, storage class, website redirect location or encryption attributes.
。
或者你可以使用copy_from
,在评论中指出由佐敦菲利普斯:
s3 = boto3.resource("s3")
object = s3.Object(bucket_name, key)
object.copy_from(CopySource={'Bucket': bucket_name,
'Key': key},
MetadataDirective="REPLACE",
ContentType="application/pdf")
复制也在资源中。 [docs](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Object.copy_from) –
@JordonPhillips更好,谢谢!如果你想补充说,作为答案,我会接受 – leo