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?
Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.
The string field is used for allowing users to enter unformatted text information into your form in a limited fashion. Creating multiple strings is useful for collecting directed information, such as answers from your user requiring single words or brief sentences.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With