我正在制作一个数据可视化工具,它接受用户的输入(在计算机上选择一个文件);使用 Pandas、Numpy 等在 Python 中处理它;并在本地服务器的浏览器中显示数据。
使用 HTML 输入表单选择文件后,我无法访问数据。
HTML 格式:
<form action="getfile" method="POST" enctype="multipart/form-data">
Project file path: <input type="file" name="myfile"><br>
<input type="submit" value="Submit">
</form>
flask 路由:
@app.route("/")
def index():
return render_template('index.html')
@app.route('/getfile', methods=['GET','POST'])
def getfile():
if request.method == 'POST':
result = request.form['myfile']
else:
result = request.args.get['myfile']
return result
这将返回“错误请求浏览器(或代理)发送了该服务器无法理解的请求。”错误。我已经尝试了多种不同的方法来从文件中获取数据并简单地将其打印到屏幕上以开始,并且收到了一系列错误,包括“TypeError:'FileStorage'对象不可调用”和“ImmutableMultiDict'对象不可调用”。任何有关如何正确处理此任务的指示都将受到赞赏。
请您参考如下方法:
试试这个。最近几天我一直在保存和解压缩文件。如果您对这段代码有任何疑问,请告诉我:)
我建议将文件保存在磁盘上然后读取它。如果您不想这样做,则不需要。
from flask import Flask, render_template, request
from werkzeug import secure_filename
@app.route('/getfile', methods=['GET','POST'])
def getfile():
if request.method == 'POST':
# for secure filenames. Read the documentation.
file = request.files['myfile']
filename = secure_filename(file.filename)
# os.path.join is used so that paths work in every operating system
file.save(os.path.join("wherever","you","want",filename))
# You should use os.path.join here too.
with open("wherever/you/want/filename") as f:
file_content = f.read()
return file_content
else:
result = request.args.get['myfile']
return result
正如 zvone 在评论中建议的那样,我也建议不要使用 GET 上传文件。
Uploading files
os.path by Effbot
编辑:-
您不想保存文件。
Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server.
我从 Flask 文档中得到了这个。由于它是一个 Python 文件,您可以直接在其上使用 file.read() 而无需 file.save()。
另外,如果您需要保存一段时间然后删除它,您可以在保存后使用os.path.remove 删除文件。 Deleting a file in Python
