Flask WTForms: Why is my POST request to upload a file not sending the file data?

 ̄綄美尐妖づ 提交于 2019-12-01 05:36:00

First of all, check if your data gets POST request on that route. Second, I think you don't need to pass request.form to ScanForm, you just need to instantiate it like:

def add():
    """Add a scan."""
    form = ScanForm()
    ...

To check what gets posted with form, instead of

if form.validate_on_submit():

you can use, and print form.scan_file.data

if form.is_submitted():
    print(form.scan_file.data)

Lastly, you can render input file with {{scan_form.scan_file }} or <input type="file" name="scan_file"> (name attribute of input element should be equal to "scan_file")

Here is my example:

Form:

class ArticleForm(FlaskForm):
    article_image = FileField('Article_image', validators=[FileRequired()])

Form in template:

<form action="" method="post" enctype="multipart/form-data">
    {{ article_form.csrf_token }}
    {{ article_form.article_image }}
    <input type="submit" value="submit"/>
</form>

Controller (saving file):

article_form = ArticleForm()

        if article_form.validate_on_submit():

            f = article_form.article_image.data
            name = current_user.username + "__" + f.filename
            name = secure_filename(name)
            f.save(os.path.join("./static/article_images/", name))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!