I am trying to upload a web page to an S3 bucket using Amazon's Boto3 SDK for Python.
I am having trouble setting the Content-Type
. AWS keeps creating a new metadata key for Content-Type
in addition to the one I'm specifying using this code:
# Upload a new file
data = open('index.html', 'rb')
x = s3.Bucket('website.com').put_object(Key='index.html', Body=data)
x.put(Metadata={'Content-Type': 'text/html'})
Any guidance of how to set Content-Type
to text/html
would be greatly appreciated.
When you upload content to AWS S3, the object can be assigned a MIME type that describes the format of the contents. The transfer service automatically applies content types to objects as they are uploaded, with content types assigned from the following list: 3dm. x-world/x-3dmf.
Boto3 is the name of the Python SDK for AWS. It allows you to directly create, update, and delete AWS resources from your Python scripts.
Content-Type
isn't custom metadata, which is what Metadata
is used for. It has its own property which can be set like this:
bucket.put_object(Key='index.html', Body=data, ContentType='text/html')
Note: .put_object()
can set more than just Content-Type
. Check out the Boto3 documentation for the rest.
You can also do it with the upload_file()
method and ExtraArgs
keyword (and set the permissions to World read as well):
import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('source_file_name.html', 'my.bucket.com', 'aws_file_name.html', ExtraArgs={'ContentType': "application/json", 'ACL': "public-read"} )
Eample using Boto3 (2022)- Use "ExtraArgs" parameter
s3 = boto3.client('s3', aws_access_key_id = AWS_ACCESS_KEY_ID, aws_secret_access_key = AWS_SECRET_ACCESS_KEY, region_name = "us-east-1")
s3.upload_file(file_path, s3_bucket, file_name, ExtraArgs={'ContentType': "application/json"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With