【问题标题】:How do you upload modified image directly to s3 bucket using python flask如何使用 python flask 将修改后的图像直接上传到 s3 存储桶
【发布时间】:2023-04-03 21:22:01
【问题描述】:

我试图简单地修改通过表单上传的图像(调整大小),然后直接上传到 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

【问题讨论】:

    标签: python python-3.x amazon-s3 flask python-imaging-library


    【解决方案1】:

    boto3包中的字节日期使用upload_fileobj函数如下:

    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 configure 的 AWS CLI 设置 API 密钥,例如 AWS ACCESS KEY 和 SECRET KEY。

    【讨论】:

    • 请查看更新功能。仍然不适合我。
    • 你应该提供更多信息为什么不工作和如果发生错误。并且上传文件 obj 需要字节类型而不是文件。如果你想上传文件,那么你需要upload_file。
    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2019-06-12
    • 1970-01-01
    • 2019-05-16
    • 2021-11-15
    • 2020-12-30
    相关资源
    最近更新 更多