Get an uploaded file from a WTForms field

Kevin Q picture Kevin Q · May 16, 2015 · Viewed 24.3k times · Source

In the Flask docs, the file upload example uses <input type="file" name="file"> then request.files['file'] to get the file. I'm using a WTForms FileField. How do I get the uploaded file when using WTForms rather than writing the input html myself?

Answer

davidism picture davidism · May 16, 2015

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>