From ebd48fde403d3075ca42e0c5901f170fe41fd25e Mon Sep 17 00:00:00 2001 From: shaurya dhaka Date: Wed, 31 Jan 2024 15:15:59 +0530 Subject: [PATCH] Add ContentType in S3 upload (#42) Co-authored-by: Amin Alaee --- fastapi_storages/s3.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/fastapi_storages/s3.py b/fastapi_storages/s3.py index a9b760f..c11ad8b 100644 --- a/fastapi_storages/s3.py +++ b/fastapi_storages/s3.py @@ -1,3 +1,4 @@ +import mimetypes import os from pathlib import Path from typing import BinaryIO @@ -18,6 +19,8 @@ class S3Storage(BaseStorage): Requires `boto3` to be installed. """ + default_content_type = "application/octet-stream" + AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "") """AWS access key ID. Either set here or as an environment variable.""" @@ -110,8 +113,12 @@ def write(self, file: BinaryIO, name: str) -> str: file.seek(0, 0) key = self.get_name(name) - - self._bucket.upload_fileobj(file, key, ExtraArgs={"ACL": self.AWS_DEFAULT_ACL}) + content_type, _ = mimetypes.guess_type(key) + params = { + "ACL": self.AWS_DEFAULT_ACL, + "ContentType": content_type or self.default_content_type, + } + self._bucket.upload_fileobj(file, key, ExtraArgs=params) return key def generate_new_filename(self, filename: str) -> str: