AWS Content Type Settings in S3 Using Boto3

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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"} )

Method 3

Here, data is an opened file, not its content:

# Upload a new file
data = open('index.html', 'rb')

To read a (binary) file:

import io

with io.open("index.html", mode="rb") as fd:
    data = fd.read()

It will be better that way.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x