[英]How to upload a file from a Flask's HTML form to an S3 bucket using python?
I have an HTML form (implemented in Flask) for uploading files.我有一个用于上传文件的 HTML 表单(在 Flask 中实现)。 And I want to store the uploaded files directly to S3.我想将上传的文件直接存储到 S3。
The relevant part of the Flask implementation is as follows: 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>'
I then use boto3
to upload the file to S3 as follows:然后我使用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)
file
is a werkzeug.datastructures.FileStorage
object. file
是一个werkzeug.datastructures.FileStorage
对象。
But I get the following error when uploading the file to S3:但是在将文件上传到 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
.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
。
How can I upload the file to S3?如何将文件上传到 S3?
Since you are using Flask web framework, the file
variable is of type werkzeug.datastructures.FileStorage .由于您使用的是 Flask Web 框架,因此file
变量的类型为werkzeug.datastructures.FileStorage 。
I think the problem is that the put()
method expects a byte sequence or a file-like object as its Body
argument.我认为问题在于put()
方法需要一个字节序列或一个类似文件的对象作为它的Body
参数。 So, it does not know what to do with the Flask's FileStorage
object.因此,它不知道如何处理 Flask 的FileStorage
对象。
A possible solution could be to use file.read()
to get a sequence of bytes and then pass it to put()
:一种可能的解决方案是使用file.read()
获取字节序列,然后将其传递给put()
:
bucket.Object(file.filename).put(Body=file.read())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.