【问题标题】:flask wtf upload image file to aws s3烧瓶wtf将图像文件上传到aws s3
【发布时间】: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


【解决方案1】:

Access_ID 和秘密 ID 指的是您的 aws 用户访问 ID 和秘密密钥,因为 boto3 将使用您分配给它的用户使用它来访问您的 aws s3。

s3 = boto3.resource("s3", aws_access_key_id=os.getenv("ACCESS_ID"), aws_secret_access_key=os.getenv("ACCESS_SECRET_ID"))

s3.Bucket("[NAME OF BUCKET]").put_object(Key="images/"+request.files["image"].filename, Body=request.files["image"] )

确保您在表单下、jinja 下包含“enctype”,例如

<form method="POST" action="" enctype="multipart/form-data">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 2014-02-09
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多