Get an uploaded file from a WTForms field Get an uploaded file from a WTForms field flask flask

Get an uploaded file from a WTForms field


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].

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.

from flask import url_for, redirect, render_templatefrom flask_wtf import FlaskFormfrom flask_wtf.file import FileFieldfrom werkzeug.utils import secure_filenameclass 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>