all that is technology

Setting content-type for files uploaded to S3


While uploading files to AWS S3 using Python Boto3 library, it would by default set the content-type as binary. Below snippet would set the appropriate content type based on the file extension.

import mimetypes
file_mime_type, _ = mimetypes.guess_type(filename)
bucket_obj.upload_file(local_path, s3_path, ExtraArgs={'ContentType': file_mime_type})

The above snippet would predict most of the common mime types. In case if some mime types are missing, it could be fixed by explicitly adding the type. Put the below snippet before calling guess_type method.

mimetypes.add_type('application/json', '.json')

Hope this helps!