34
votes

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.

3

3 Answers

54
votes

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.

53
votes

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

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.