Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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_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

Is there a method for this I have missed in boto3?

Related questions:

  • How to set Content-Type on upload
  • How to set the content type of an S3 object via the SDK?
like image 274
leo Avatar asked Jun 10 '16 09:06

leo


People also ask

How do I change storage class on S3 Boto3?

You can also change the storage class of an object that is already stored in Amazon S3 by copying it to the same key name in the same bucket. To do that, you use the following request headers in a PUT Object copy request: x-amz-metadata-directive set to COPY.

Does Put_object overwrite?

put_object` does not overwrite the existing data in the bucket.

What is Boto3 resource (' S3 ')?

​Boto3 is the official AWS SDK for Python, used to create, configure, and manage AWS services. The following are examples of defining a resource/client in boto3 for the Weka S3 service, managing credentials, and pre-signed URLs, generating secure temporary tokens, and using those to run S3 API calls.


1 Answers

In addition to @leo's answer, be careful if you have custom metadata on your object. To avoid side effects, I propose adding Metadata=object.metadata in the leo's code otherwise you could lose previous custom metadata:

s3 = boto3.resource("s3")
object = s3.Object(bucket_name, key)
object.copy_from(
          CopySource={'Bucket': bucket_name, 'Key': key},
          Metadata=object.metadata,
          MetadataDirective="REPLACE",
          ContentType="application/pdf"
)
like image 174
cannereau Avatar answered Oct 05 '22 20:10

cannereau