【问题标题】:Upload files to S3 with Python (keeping the original folder structure) with correct MIME type使用正确的 MIME 类型使用 Python 将文件上传到 S3(保持原始文件夹结构)
【发布时间】:2018-11-24 23:22:45
【问题描述】:

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

【问题讨论】:

    标签: python amazon-s3 mime-types boto3


    【解决方案1】:
    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')
    

    【讨论】:

      猜你喜欢
      • 2011-06-09
      • 2011-01-17
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      相关资源
      最近更新 更多