Flask将图像上传到S3而不将其保存到本地文件系统 [英] Flask Upload Image to S3 without saving it to local file system

查看:52
本文介绍了Flask将图像上传到S3而不将其保存到本地文件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将用户提交的照片上传到s3存储桶.但是我一直收到以下错误:

I need to upload a a user submitted photo to an s3 bucket. However I keep getting the following error:

TypeError: expected str, bytes or os.PathLike object, not FileStorage

如何将文件存储为字符串/字节而不是文件存储?相关代码如下:

How am I able to store the file as string/bytes instead of FileStorage? The relevent code is as follows:

@user_api.route('upload-profile-photo', methods=['PUT'])
@Auth.auth_required
def upload_profile_photo():
  """
  Upload User Profile Photo
  """
  key = Auth.auth_user()
  bucket = 'profile-photos'
  content_type = request.mimetype
  image_file = request.files['file']
  client = boto3.client('s3',
                        region_name='sfo2',
                        endpoint_url='https://example.xxx.amazonaws.com',
                        aws_access_key_id=os.environ['ACCESS_KEY'],
                        aws_secret_access_key=os.environ['SECRET_KEY'])
  with open(image_file, "rb") as f:
    client.upload_fileobj(
        bucket,
        f,
        key,
        ExtraArgs={'ACL': 'public-read', 'ContentType': content_type}
    )

  return custom_response({'message': 'image uploaded'}, 200)

推荐答案

i要使用 FileStorage 实现此目的,我使用 put_object()方法:

iTo achieve that with a FileStorage, I use the method put_object():

from werkzeug import secure_filename

@user_api.route('upload-profile-photo', methods=['PUT'])
@Auth.auth_required
def upload_profile_photo():
    """
    Upload User Profile Photo
    """
    key = Auth.auth_user()
    bucket = 'profile-photos'
    content_type = request.mimetype
    image_file = request.files['file']

    client = boto3.client('s3',
                          region_name='sfo2',
                          endpoint_url='https://example.xxx.amazonaws.com',
                          aws_access_key_id=os.environ['ACCESS_KEY'],
                          aws_secret_access_key=os.environ['SECRET_KEY'])

    filename = secure_filename(image_file.filename)  # This is convenient to validate your filename, otherwise just use file.filename

    client.put_object(Body=image_file,
                      Bucket=bucket,
                      Key=filename,
                      ContentType=content_type)

    return custom_response({'message': 'image uploaded'}, 200)

注意对 secure_filename()的调用 是可选的(您可以简单地传递 image_file.filename ),但是可以很方便地验证文件名.否则,最好添加一些异常处理,但这里的基本思路是:无需 open()文件(该文件需要存储在本地).

Note the call to secure_filename() is optional (you can simply pass image_file.filename), but can be very handy to validate the filename. Otherwise it would be nice to add some exception handlings, but the rough idea is here: no need to open() the file (that would need to be stored locally).

我鼓励您查看

I encourage to have a look at the documentation here, to understand the difference with upload_fileobj()

这篇关于Flask将图像上传到S3而不将其保存到本地文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆