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

2024-04-19 00:57:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

烧瓶实施的相关部分如下所示:

@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)

file是一个werkzeug.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


Tags: 文件keyformaws表单s3bucketaccess
1条回答
网友
1楼 · 发布于 2024-04-19 00:57:40

由于您使用的是Flask web framework,file变量的类型为werkzeug.datastructures.FileStorage

我认为问题在于^{}方法需要一个字节序列或类似文件的对象作为其Body参数。因此,它不知道如何处理Flask的FileStorage对象

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

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

相关问题 更多 >