Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an uploaded file from a WTForms field

Tags:

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?

like image 655
Kevin Q Avatar asked May 16 '15 18:05

Kevin Q


People also ask

How do I access my uploaded files on flask?

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.

What is Stringfield?

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.


1 Answers

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> 
like image 154
davidism Avatar answered Sep 22 '22 05:09

davidism