我有一个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)
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?
答案 0 :(得分:1)
由于您使用的是Flask网络框架,因此file
变量的类型为werkzeug.datastructures.FileStorage。
我认为问题在于put()
方法期望字节序列或类似文件的对象作为其Body
参数。因此,它不知道如何处理Flask的FileStorage
对象。
可能的解决方案是使用file.read()
获取字节序列,然后将其传递给put()
:
bucket.Object(file.filename).put(Body=file.read())