我的代码目前接收一个文件,并将其保存到预设目录,但是否可以只使用该文件(读取文件)而不保存它?
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "yatta"
else:
return "file not allowed"
return render_template("index.html")
我都试过了
file.read() 和 file.stream.read() 但返回值为空。我验证该文件存在于上传的目录中,并看到该文件不为空。
最佳答案
我知道这已经很过时了,但是为了人们登陆这里进行类似的查询,如果您想保存并在病房后阅读您的文件,请在这里。似乎是 Werkzeug 的 FileStorage 类(这是在 Flask 中处理上传文件的类)在每次操作(保存或读取)后指向到文件末尾。所以我们必须在执行任何后续操作之前将指针向上移动到文件的开头。我在下面的回答中使用了 python 的 pandas,因为我通常将 csv 读入数据框。
import pandas as pd
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
## snippet to read code below
file.stream.seek(0) # seek to the beginning of file
myfile = file.file # will point to tempfile itself
dataframe = pd.read_csv(myfile)
## end snippet
return "yatta"
else:
return "file not allowed"
return render_template("index.html")
关于python flask上传文件但不保存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438141/