默认情况下,如果未显式设置 ContentType
,boto3
会将文件上传到 s3
,内容类型为 Content-Type:binary/八位字节流
。当使用 s3 作为静态托管时,这并不好。截至目前,there is PR为此。
最佳答案
import boto3
import os
import mimetypes
def upload_files(path):
session = boto3.Session(
aws_access_key_id='YOUR_AWS_ACCESS_KEY_ID',
aws_secret_access_key='YOUR_AWS_SECRET_ACCESS_KEY_ID',
region_name='YOUR_ACCOUNT_REGION'
)
s3 = session.resource('s3')
bucket = s3.Bucket('YOUR_BUCKET_NAME')
for subdir, dirs, files in os.walk(path):
for file in files:
full_path = os.path.join(subdir, file)
file_mime = mimetypes.guess_type(file)[0] or 'binary/octet-stream'
with open(full_path, 'rb') as data:
bucket.put_object(Key=full_path[len(path)+1:], Body=data, ContentType=file_mime)
if __name__ == "__main__":
upload_files('/path/to/your/folder')
关于python - 使用Python将文件上传到S3(保留原始文件夹结构)并具有正确的MIME类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870070/