读取文件数据而不将其保存在 Flask 中 [英] Read file data without saving it in Flask
问题描述
我正在编写我的第一个烧瓶应用程序.我正在处理文件上传,基本上我想要的是在不保存的情况下读取上传文件的数据/内容,然后将其打印在结果页面上.是的,我假设用户总是上传一个文本文件.
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)
现在,我正在保存文件,但我需要的是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
包含 stream
字段.这个对象必须扩展IO或文件对象,所以它必须包含read
等类似的方法.FileStorage
还扩展了 stream
字段对象属性,因此您可以使用 file.read()
代替 file.stream.read()代码>.您也可以使用
save
参数和 dst
参数作为 StringIO
或其他 IO 或文件对象来复制 FileStorage.stream
到另一个 IO 或文件对象.
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.
参见文档:http://flask.pocoo.org/docs/api/#flask.Request.files 和 http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.
这篇关于读取文件数据而不将其保存在 Flask 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!