读取文件数据而不保存在Flask中 [英] Read file data without saving it in Flask

查看:945
本文介绍了读取文件数据而不保存在Flask中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写我的第一个烧瓶应用程序。我正在处理文件上传,基本上我想要的是读取上传的文件的数据/内容而不保存,然后打印在结果页面上。是的,我假设用户总是上传一个文本文件。



这是我使用的简单的上传功能:

  @ app.route('/ upload /',methods = ['GET','POST'])
def upload():
if request.method =='POST':
file = request.files ['file']
if file:
filename = secure_filename(file.filename)
file.save os.path.join(app.config ['UPLOAD_FOLDER'],filename))
a ='file uploaded'

return render_template('upload.html',data = a)

现在我正在保存文件,但是我需要的是包含内容的'a'变量/ data of the file ..有什么想法吗?

解决方案

FileStorage 包含 stream 字段。该对象必须扩展IO或文件对象,所以它必须包含 read 和其他类似的方法。 FileStorage 也扩展了 stream 字段对象属性,所以你可以使用 file.read() 改为 file.stream.read()。你也可以把 save 参数作为 StringIO 使用 dst 或其他IO或文件对象,以将 FileStorage.stream 复制到另一个IO或文件对象。



a href =http://flask.pocoo.org/docs/api/#flask.Request.files =noreferrer> http://flask.pocoo.org/docs/api/#flask.Request。文件和 http://werkzeug.pocoo.org/docs/ datastructures /#werkzeug.datastructures.FileStorage


I am writing my first flask application. I am dealing with file uploads, and basically what I want is to read the data/content of the uploaded file without saving it and then print it on the resulting page. Yes, I am assuming that the user uploads a text file always.

Here is the simple upload function i am using:

@app.route('/upload/', methods=['GET', 'POST'])
def upload():
   if request.method == 'POST':
      file = request.files['file']
      if file:
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        a = 'file uploaded'

return render_template('upload.html', data = a)

Right now, I am saving the file, but what I need is that 'a' variable to contain the content/data of the file .. any ideas?

解决方案

FileStorage contains stream field. This object must extend IO or file object, so it must contain read and other similar methods. FileStorage also extend stream field object attributes, so you can just use file.read() instead file.stream.read(). Also you can use save argument with dst parameter as StringIO or other IO or file object to copy FileStorage.stream to another IO or file object.

See documentation: http://flask.pocoo.org/docs/api/#flask.Request.files and http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.

这篇关于读取文件数据而不保存在Flask中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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