Python 从 WTForms 字段获取上传的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30279473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get an uploaded file from a WTForms field
提问by Kevin Q
In the Flask docs, the file upload example uses <input type="file" name="file">
then request.files['file']
to get the file. I'm using a WTForms FileField. How do I get the uploaded file when using WTForms rather than writing the input html myself?
在 Flask 文档中,文件上传示例使用<input type="file" name="file">
thenrequest.files['file']
来获取文件。我正在使用 WTForms FileField。使用WTForms而不是自己编写输入html时如何获取上传的文件?
采纳答案by davidism
request.files
is a dictionary where the keys are the names of the file fields. You can get the name of a WTForms field with my_form.my_field.name
. So you can access the data uploaded from that field with request.files[my_form.my_field.name]
.
request.files
是一个字典,其中键是文件字段的名称。您可以使用my_form.my_field.name
. 因此,您可以访问从该字段上传的数据request.files[my_form.my_field.name]
。
Rather than using the WTForms FileField, you can use the Flask-WTF FileField instead. It provides a data
attribute that gets the file data for you. This is described in the documentation.
您可以使用 Flask-WTF FileField 而不是使用 WTForms FileField。它提供了一个data
为您获取文件数据的属性。 这在文档中有所描述。
from flask import url_for, redirect, render_template
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from werkzeug import secure_filename
class UploadForm(FlaskForm):
file = FileField()
@app.route('/upload', methods=['GET', 'POST'])
def upload():
form = UploadForm()
if form.validate_on_submit():
filename = secure_filename(form.file.data.filename)
form.file.data.save('uploads/' + filename)
return redirect(url_for('upload'))
return render_template('upload.html', form=form)
<html>
<head>
<title>Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.file }}
<input type="submit">
</form>
</body>
</html>