读取文件数据而不保存在Flask中 [英] Read file data without saving it in 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 ..有什么想法吗?
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屋!