0

I'm trying to save multiple files through WTForm. Since there is no documentation on how you need to use MultipleFileField I looked on SO and came accross multiple answers. This one looked promising but it doesn't work. The file variable is a string and thus the code doesn't work.

class CreatePostForm(FlaskForm):
    files = MultipleFileField('Upload files', validators={DataRequired()})
    submit = SubmitField(_l('Submit'))
@app.route('/create_post', methods=['GET', 'POST'])
@login_required
def create_post():
    form = CreatePostForm()
    if form.validate_on_submit():
        files_filenames = []
        for file in form.files.data:
            file_filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_filename))
            files_filenames.append(file_filename)
        return redirect(url_for('index'))
    return render_template('create_post.html', form=form)
John
  • 25
  • 4
  • Does your forrm have the `enctype = "multipart/form-data"` attribute ? – Kate Jun 19 '21 at 15:11
  • It did not, I assumed it would add that automatically when using the MultipleFileField in the form. – John Jun 20 '21 at 17:07
  • I am not sure about that, WTF can create the form fields as necessary but you should still add the
    tags in your page. - see: https://pythonhosted.org/Flask-WTF/form.html (this is for the Flask version but should be equally relevant). If in doubt, look at the resulting HTML source code in your browser.
    – Kate Jun 20 '21 at 17:14

1 Answers1

0

Turns out the MultipleFileField doesn't add the enctype="multipart/form-data" attribute to the html form. You have to do this manually to make this work.

So the above code works with this html page.

<form action="" method="post" class="form" role="form" enctype="multipart/form-data">
{{ wtf.quick_form(form) }}
</form>
John
  • 25
  • 4