gpt4 book ai didi

python - 如何使用 python Flask 将修改后的图像直接上传到 s3 存储桶

转载 作者:行者123 更新时间:2023-12-01 07:14:18 25 4
gpt4 key购买 nike

我试图简单地修改通过表单上传的图像(调整其大小),然后直接上传到 s3 存储桶。当我将文件保存在本地时,我使用下面的示例有效,但在尝试上传到 s3 时遇到问题。

 def _image_resize(temp_path, file, image_base, extension):
image = Image.open(file)
wpercent = (image_base / float(image.size[0]))
hsize = int((float(image.size[1]) * float(wpercent)))
image = image.resize((image_base, hsize), Image.ANTIALIAS)
modified_file_path = os.path.join(
temp_path, file.filename + '.' + extension + '.png'
)
image.save(modified_file_path)
with open(modified_file_path, 'rb') as data:
upload_file_to_s3(data, Config.S3_BUCKET_NAME)
return

def upload_file_to_s3(file, bucket_name, acl="public-read"):
"""
Docs: http://boto3.readthedocs.io/en/latest/guide/s3.html
"""

try:

s3.upload_fileobj(
file,
bucket_name,
ExtraArgs={
"ACL": acl
}
)

except Exception as e:
print("Something Happened: ", e)
return e

return

最佳答案

使用 upload_fileobj 函数获取 boto3 包中的字节日期,如下所示:

import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
obj = bucket.Object('mykey')

with open('filename', 'rb') as data:
obj.upload_fileobj(data)

您必须使用 AWS CLI 和 aws configure 设置 API key ,例如 AWS ACCESS KEY 和 SECRET KEY。

关于python - 如何使用 python Flask 将修改后的图像直接上传到 s3 存储桶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com