How do I set the Content-Type of an existing S3 key with boto3?

后端 未结 1 1011
野的像风
野的像风 2021-01-02 06:32

I want to update the Content-Type of an existing object in a S3 bucket, using boto3, but how do I do that, without having to re-upload the file?

    file_obj         


        
相关标签:
1条回答
  • 2021-01-02 07:04

    There doesn't seem to exist any method for this in boto3, but you can copy the file to overwrite itself.

    To do this using the AWS low level API through boto3, do like this:

    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)
    

    The MetadataDirective="REPLACE" turns out to be required for S3 to overwrite the file, otherwise you will get an error message saying 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. .

    Or you can use copy_from, as pointed out by Jordon Phillips in the comments:

    s3 = boto3.resource("s3")
    object = s3.Object(bucket_name, key)
    object.copy_from(CopySource={'Bucket': bucket_name,
                                 'Key': key},
                     MetadataDirective="REPLACE",
                     ContentType="application/pdf")
    
    0 讨论(0)
提交回复
热议问题