【问题标题】:Uploaded file from Html form to S3 using python but getting blank text file使用python将文件从Html表单上传到S3但得到空白文本文件
【发布时间】:2020-02-17 12:55:09
【问题描述】:

我有一个用于上传文件的 HTML 表单(在 Flask 中实现)。我想将上传的文件直接存储到S3。

Flask实现的相关部分如下:

@app.route('/',methods=['GET'])
def index():
    return '<form method="post" action="/upload" enctype="multipart/form-data"><input type="file" name="file" /><button>Upload</button></form>'

然后我使用boto3将文件上传到S3如下:

@app.route('/upload',methods = ['GET','POST'])
    def upload_file():
        if request.method =='POST': 
            file = request.files['file']
            if file:
                filename = secure_filename(file.filename)
                #file.save(os.path.join(UPLOAD_FOLDER,filename))
                s3_resource = boto3.resource('s3',aws_access_key_id='****',
                            aws_secret_access_key='*****')
                buck = s3_resource.Bucket('MY_BUCKET_NAME')
                buck.Object(file.filename).put(Body=file.read())

            return 'uploaded'

文件已成功上传到 S3 存储桶中。当试图打开该文件时,它会以空白文本文件的形式打开。即使我尝试在put() 方法中设置ContentType,但仍然无法正常工作。

它的大小也显示0B

请告诉我出了什么问题?

谢谢!

【问题讨论】:

  • 您是否尝试向 Python 添加调试代码以显示 file 变量中的内容?
  • 是的,file 变量是所选文件的FileStroage,因为我正在使用Flask 框架。但是s3的put()方法接受file -like object所以我使用file.read()
  • 您还在哪里使用过file.read()?你能显示整个代码吗?
  • 另一种方法是将文件保存到/tmp/ 目录,然后从磁盘上传文件。 flask.request.files Python Example
  • @Debendra,我使用file.read() 仅在put() 方法中传递Body 属性。我已经更新了完整的/upload 路线。

标签: python amazon-s3 boto3


【解决方案1】:

你肯定已经到了流的末尾。

file.read() 没有要读取的字节,因此 s3 上的文件为空。

要么尝试file.seek(0) 重置流,要么您必须确保您正在读取文件一次。

例如:

# You just read the file here.
file.save(os.path.join(UPLOAD_FOLDER, filename))
# file.read() is empty now, you reached to the end of stream

# You are again reading the file here but file.read() is empty, so reset the stream.
file.seek(0)
# file.read() is back to original now
buck.Object(file.filename).put(Body=file.read())

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多