2016-06-10 47 views
3

我想使用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?

相关的问题:那里似乎

回答

6

不存在任何方法,这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") 
+1

复制也在资源中。 [docs](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Object.copy_from) –

+0

@JordonPhillips更好,谢谢!如果你想补充说,作为答案,我会接受 – leo

-2

尝试

file_object.put(ContentType='<specific_content/type>') 

由文档here的描述下。

+0

不,内容类型不能像这样设置(请参阅上面的链接问题),因此这个问题... – leo

+0

我认为它可以是。请看看这些文档。 https://boto3.readthedocs.io/en/latest/guide/migrations3.html#key-metadata – Darwesh

+0

boto3中称为“元数据”的东西是您可以添加到S3对象的自定义元数据,所以不,内容键入,对不起。我同意参数的命名可能会令人困惑,但 – leo

相关问题