Flask file not detecting on upload

2019-02-19 21:59发布

I made a flask_wtf Form with this field:

logo_image = FileField('logo_image', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')])

My form looks like this:

<form action="" method="POST" name="app_branding" enctype="multipart/form-data">
    {{ form.csrf_token }}
    {{ form.brand.label }} {{ form.brand }}
    {{ form.logo_image.label }} {{ form.logo_image }}
    {{ form.title_text.label }} {{ form.title_text }}
    {{ form.first_paragraph.label }} {{ form.first_paragraph }}
    {{ form.faq.label }} {{ form.faq }}
    {{ form.privacy_policy.label }} {{ form.privacy_policy }}
    {{ form.success_message.label }} {{ form.success_message }}
    {{ form.submit.label }} {{ form.submit }}
</form>

For debugging, in my view, I put:

@expose('/', methods=['GET', 'POST'])
def index(self):
    form = BrandForm(request.form)
    print(form.validate())
    print(form.errors)
    print("request.files")
    print(request.files)

And in the console I get the message that logo_image is required, even though it is there in request.files:

False
{'logo_image': ['This field is required.']}
request.files
ImmutableMultiDict([('logo_image', <FileStorage: u'20140725_095232.jpg' ('image/jpeg')>)])

How do I get the FileRequired() method to detect the file?

1条回答
Explosion°爆炸
2楼-- · 2019-02-19 22:45

request.form only contains form input data. request.files contains file upload data. You need to pass the combination of both to the form. Since your form inherits from Flask-WTF's Form (now called FlaskForm), it will handle this automatically if you don't pass anything to the form.

form = BrandForm()

if form.validate_on_submit():
    ...

Without Flask-WTF, use a CombinedMultiDict to combine the data and pass that to the form.

from werkzeug.datastructures import CombinedMultiDict

form = BrandForm(CombinedMultiDict((request.files, request.form)))

if request.method == 'POST' and form.validate():
    ...
查看更多
登录 后发表回答