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_template
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from werkzeug.utils import secure_filename

class 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>

Leave a Comment

tech