2

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'",

1 Answers1

3

Use

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

See AWS Content Type Settings in S3 Using Boto3

Gonzalo Odiard
  • 1,238
  • 12
  • 19
  • this doesn't throw an error but the type is still undefined in S3 –  Oct 21 '21 at 07:14
  • you can try also upload_file() where you set the filename so your code is much simpler https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.upload_file – Gonzalo Odiard Oct 21 '21 at 17:03