Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 385
Rupert Avatar asked Dec 31 '15 19:12

Rupert


People also ask

What is content type in AWS S3?

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.

What is Boto3 client (' S3 ')?

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.


3 Answers

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.

like image 200
Michael - sqlbot Avatar answered Oct 17 '22 08:10

Michael - sqlbot


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"} )
like image 28
Jheasly Avatar answered Oct 17 '22 08:10

Jheasly


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"})
like image 1
Karthik Pillai Avatar answered Oct 17 '22 09:10

Karthik Pillai