greyli / helloflask

Hello, Flask!
https://docs.helloflask.com
MIT License
1.87k stars 2.53k forks source link

多文件上传的视图函数样例中'确保字段包含文件数据'的if条件判断语句实测无效 #220

Closed lqdflying closed 3 years ago

lqdflying commented 3 years ago

demo代码位置: https://github.com/greyli/helloflask/blob/8808244ff32392bff3da05a1df14b7431e0f87e7/demos/form/app.py#L143

测试过程:

  1. 删除forms.py中MultiUploadForm()类定义下中的validators=[DataRequired()],最终代码改为如下:
    # multiple files upload form
    class MultiUploadForm(FlaskForm):
    photo = MultipleFileField('Upload Image')
    submit = SubmitField()
  2. 修改demo中此处位置的代码如下:
        if True:
            flash('This field is required.but the if conditional statements always is %s'%('photo' not in request.files))
            return redirect(url_for('multi_upload'))
  3. flask run后,http://127.0.0.1:5000/multi-upload页面点击submit,flash永远是:

This field is required.but the if conditional statements always is False

lqdflying commented 3 years ago

用大佬书里教的技巧,用非常垃圾的代码修正了这个问题,实测ok:

            # check if the post request has the file part
            if not f[0].filename:
                flash('至少要上传一个文件!')
                return redirect(url_for('multi_upload_adv'))
greyli commented 3 years ago

谢谢,用你的方法修正了。当时不知道为什么脑子发热写了这个判断,而下面注释掉的代码却很接近你的方法。我一直在等 Flask-WTF 这个多文件验证支持的 PR 被合并,这样就不用麻烦写这么多处理逻辑了。