【发布时间】:2020-06-28 19:00:51
【问题描述】:
我想使用预签名的 url 将图像上传到 aws s3,并且图像仅由用户选择。 所以我使用flask-wtf文件字段制作文件输入字段。 用户提交表单(PostForm)后,我想获取图像的数据并发送到 presigned-url。 但我不知道如何从表单中获取图像文件的信息。
请帮帮我!!!
我使用了以下教程中的示例代码。但不同的是我使用的是flask-wtf而不是本地图像文件。
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html
在下面的代码中,问题所在。
files = {'file': (save_objectname, image.read())}
http_response = requests.post(response['url'], data=response['fields'], files=files)
当我print(image.read())
表明
b''
我该如何解决???
def create_post():
form = PostForm()
save_post_foldername = 'post_images'
if form.validate_on_submit():
if form.post_image.data:
image_file = form.post_image.data
save_post_objectname = generate_filename(image_file)
# Generate a presigned S3 POST URL
post_to_aws_s3(image_file, save_post_foldername, save_post_objectname)
def post_to_aws_s3(image, save_foldername, save_objectname):
fields = {
"acl": "public-read",
"Content-Type": image.content_type
}
conditions = [
{"acl": "public-read"},
{"Content-Type": image.content_type}
]
try:
response = s3_client.generate_presigned_post(
Bucket=S3_BUCKET,
Key=save_foldername+'/'+save_objectname,
Fields=fields,
Conditions=conditions,
ExpiresIn=600
)
print(response)
print(response['url'])
print(image.content_type)
#with open(image, 'rb') as f:
#files = {'file': ('abc.png', f)}
#files = {'file': (image, f)}
files = {'file': (save_objectname, image.read())}
http_response = requests.post(response['url'], data=response['fields'], files=files)
print(image.read())
except ClientError as e:
print("error")
【问题讨论】:
-
嗨,这个你搞定了吗?
标签: python-3.x amazon-s3 boto3 flask-wtforms