Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing metadata when uploading file to s3 with python

I have an html file that I am uploading to s3 using python. For some reason, s3 adds a system defined metadata saying that the file Content-Type is "binary/octet-stream": enter image description here

I need to change this value to "text/html". I can do it manually, but I want it to be done automatically when I upload the file. I tried the following code:

metadata = {
    "Content-Type": "text/html"
}
s3_file_key = str(Path("index.html"))
local_file_path = Path("~", "index.html").expanduser()
s3 = session.resource("s3")
bucket = s3.Bucket(bucket_name)
with open(local_file_path, READ_BINARY) as local_file:
    bucket.put_object(Key=s3_file_key, Body=local_file, Metadata=metadata)

but the result was that the file had 2 metadata keys:

enter image description here

I couldn't find any documentation about how to change a system defined metadata.

Thanks for the help

like image 270
Gal Itzhak Avatar asked Nov 30 '25 06:11

Gal Itzhak


2 Answers

Use MetadataDirective parameter:

bucket.put_object(Key=s3_file_key, Body=local_file, Metadata=metadata, MetadataDirective='REPLACE')

MetadataDirective -- Specifies whether the metadata is copied from the source object or replaced with metadata provided in the request ('COPY' | 'REPLACE').

S3 - Boto3 Docs

like image 61
goncuesma Avatar answered Dec 01 '25 19:12

goncuesma


I was also having a similar problem and I found out you need to use the ContentType parameter for the put_object function.

bucket.put_object(Key=s3_file_key, Body=local_file, ContentType='text/html')
like image 44
Mahkusaurelius Avatar answered Dec 01 '25 19:12

Mahkusaurelius