如何使用python将文件从Flask的HTML表单上传到S3存储桶?

时间:2020-02-15 11:36:23

标签: python flask amazon-s3 boto3

我有一个HTML表单(在Flask中实现),用于上传文件。而且我想将上传的文件直接存储到S3。

Flask实现的相关部分如下:

@app.route('/',methods=['GET'])
def index():
    return '<form method="post" action="/upload" enctype="multipart/form-data"><input type="file" name="files" /><button>Upload</button></form>'

然后我使用boto3将文件上传到S3,如下所示:

file = request.files['files']
s3_resource = boto3.resource(
    's3',
     aws_access_key_id='******',
     aws_secret_access_key='*******')

bucket = s3_resource.Bucket('MY_BUCKET_NAME')

bucket.Object(file.filename).put(Body=file)

filewerkzeug.datastructures.FileStorage对象。

但是将文件上传到S3时出现以下错误:

botocore.exceptions.ClientError: An error occurred (BadDigest) when calling the PutObject operation (reached max retries: 4): The Content-MD5 you specified did not match what we received

如何将文件上传到S3?

1 个答案:

答案 0 :(得分:1)

由于您使用的是Flask网络框架,因此file变量的类型为werkzeug.datastructures.FileStorage

我认为问题在于put()方法期望字节序列或类似文件的对象作为其Body参数。因此,它不知道如何处理Flask的FileStorage对象。

可能的解决方案是使用file.read()获取字节序列,然后将其传递给put()

bucket.Object(file.filename).put(Body=file.read())