默认情况下,如果ContentType
未明确设置,boto3
会将文件上传到s3
Content-Type: binary/octet-stream
。当使用s3
作为静态托管时,这不是很好。截至目前,there is PR为此。
答案 0 :(得分:4)
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')