使用Python(保留原始文件夹结构)将文件上载到S3并使用正确的MIME类型

时间:2018-06-15 06:17:23

标签: python amazon-s3 mime-types boto3

默认情况下,如果ContentType未明确设置,boto3会将文件上传到s3 Content-Type: binary/octet-stream。当使用s3作为静态托管时,这不是很好。截至目前,there is PR为此。

1 个答案:

答案 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')