我正在制作一个数据可视化工具,它从用户那里获取输入(在计算机上选择一个文件);使用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
这将返回&#34;错误请求浏览器(或代理)发送了此服务器无法理解的请求。&#34;错误。我已经尝试了许多不同的方法从文件中获取数据并将其打印到屏幕上以便开始,并且收到了一系列错误,包括&#34; TypeError:&#39; FileStorage&#39;对象不可调用&#34;和&#34; ImmutableMultiDict&#39;对象不可调用&#34;。任何有关如何正确处理此任务的指示都表示赞赏。
答案 0 :(得分:1)
input type=file
数据不会作为请求对象的form
字典传入。它以request.files
(请求对象中的文件字典)传入。
简单地改变:
result = request.form['myfile']
到
result = request.files['myfile']
答案 1 :(得分:1)
试试这个。我过去几天一直致力于保存和解压缩文件。如果您对此代码有任何问题,请告诉我们:)
我建议将文件保存在磁盘上,然后再将其读取。如果你不想这样做,你就不需要了。
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
您不想保存文件。
上传的文件存储在内存中或文件系统的临时位置。您可以通过查看请求对象上的files属性来访问这些文件。每个上传的文件都存储在该字典中。它的行为就像标准的Python文件对象,但它也有一个save()方法,允许您将该文件存储在服务器的文件系统上。
我从Flask文档中得到了这个。由于它是一个Python文件,因此您可以直接使用file.read()
而不使用file.save()
。
此外,如果您需要将其保存一段时间,然后稍后将其删除,则可以使用os.path.remove
在保存文件后删除该文件。 Deleting a file in Python