Welcome to our Flask tutorial on File Upload using Flask-WTF! In this lesson, we'll learn how to create a simple web application that allows users to upload files. Let's dive in!
Before we start, let's understand what Flask-WTF is. It's an extension for Flask that simplifies web forms and helps in handling file uploads.
š Note: Flask-WTF is built on top of WTForms, a powerful form validation library for Python.
First, make sure you have Python and Flask installed on your system. If not, follow the Flask Tutorial: Getting Started to set up your environment.
Next, create a new Flask project and install Flask-WTF using pip:
$ mkdir flask-file-upload
$ cd flask-file-upload
$ pip install flask flask-wtfNow, let's create our web application. In the flask-file-upload folder, create a new file named app.py.
Open app.py and let's start by defining a basic form for our file upload:
from flask import Flask, render_template, request
from wtforms import Form, FileField
from wtforms.validators import InputRequired
class UploadForm(Form):
file = FileField('Upload a file', validators=[InputRequired()])
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'š” Pro Tip: Replace 'your-secret-key' with a secure secret key for your application.
Now, create a folder named templates and create a new HTML file upload.html inside it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.file.label }}<br>
{{ form.file(size=30) }}<br>
<button type="submit">Upload</button>
</form>
</body>
</html>š Note: The enctype="multipart/form-data" attribute is necessary for file uploads.
Next, we'll handle the form submission in our Flask application:
from flask import send_file
@app.route('/upload', methods=['POST'])
def upload():
form = UploadForm(request.files)
if form.validate_on_submit():
file = form.file.data
with open('uploads/' + file.filename, 'wb') as f:
f.write(file.read())
return send_file('uploads/' + file.filename, as_attachment=True)
return render_template('upload.html', form=form)
@app.route('/')
def index():
return render_template('upload.html', form=UploadForm())š” Pro Tip: Save uploaded files in a designated folder named uploads.
Finally, let's run the application:
$ python app.pyNow, navigate to http://127.0.0.1:5000/ in your web browser to see the file upload form in action.
What is the purpose of Flask-WTF in this tutorial?
In this tutorial, we learned how to create a simple web application for file uploads using Flask and Flask-WTF. We discussed the basic structure of a file upload application, including creating a form, handling form submissions, and saving uploaded files.
šÆ Next Steps:
Happy coding! š©āš»šØāš»