Home > Back-end >  how to specify ContentType for S3 files?
how to specify ContentType for S3 files?

Time:10-22

I am trying to convert files to gzip files and then upload them to S3. When I check in S3, the files are there but they don't have a type specified. How can I specify the content type?

    for i in testList:
        with contextlib.ExitStack() as stack:
            source_file = stack.enter_context(open(i , mode="rb"))
            destination_file = io.BytesIO()
            destination_file_gz = stack.enter_context(gzip.GzipFile(fileobj=destination_file, mode='wb'))
            while True:
                chunk = source_file.read(1024)
                if not chunk:
                    break
                destination_file_gz.write(chunk)
            destination_file_gz.close()
            destination_file.seek(0)
            
            bucket.upload_fileobj(destination_file, fileName, ContentType='application/gzip')

If I add ContentType as an argument to the last line, I get an error:

"errorMessage": "bucket_upload_fileobj() got an unexpected keyword argument 'ContentType'",

CodePudding user response:

Use

bucket.upload_fileobj(destination_file, fileName,ExtraArgs={'ContentType': "application/gzip"})

See AWS Content Type Settings in S3 Using Boto3

  • Related