如果我打电话
request.files['file']
我得到了文件对象,但是
form.validate_on_submit()
仍然失败。如果请求中有文件对象,为什么失败?
表单.py
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
class ExcelForm(FlaskForm):
excel_file = FileField(validators=[
FileRequired()
])
web应用程序.py
from flask import Flask, render_template, redirect, url_for, request
from forms import ExcelForm
import pandas as pd
app = Flask(__name__)
app.config['SECRET_KEY'] = '314159265358'
@app.route('/', methods=['GET', 'POST'])
def upload():
form = ExcelForm(request.form)
if request.method == 'POST' and form.validate_on_submit():
df = pd.read_csv(form.excel_file.data)
print(df.head())
return redirect(url_for('hello', name=form.excel_file.data))
return render_template('upload.html', form=form)
@app.route('/hello/<name>')
def hello(name):
return 'hello' + name
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
{% extends "layout.html" %}
{% block content %}
<form method = "POST" enctype = "multipart/form-data">
{{ form.hidden_tag() }}
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
{% endblock content %}
我可以进入
localhost:5000/upload
没有问题。我单击浏览按钮,选择我的文件,然后单击提交按钮。
在
webapp.py
upload
表单.validate_on_submit()
失败并给我一个错误说
{'excel_file': ['This field is required.']}
我也不想将文件保存在本地以便以后读取。