0
0
Flaskframework~30 mins

File upload forms in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
File upload forms
📖 Scenario: You are building a simple web app where users can upload a profile picture. The app needs a form to select a file and a way to handle the uploaded file on the server.
🎯 Goal: Create a Flask app with a file upload form. The form should let users pick a file. The server should accept the file and save it to a folder called uploads.
📋 What You'll Learn
Create a Flask app with a route for the upload form
Add an HTML form with enctype='multipart/form-data' and a file input named file
Configure a folder path variable called UPLOAD_FOLDER to save uploaded files
Write a route to handle POST requests, save the uploaded file to UPLOAD_FOLDER
💡 Why This Matters
🌍 Real World
File upload forms are common in web apps for profile pictures, documents, or media uploads.
💼 Career
Understanding file uploads is essential for backend web developers working with user-generated content.
Progress0 / 4 steps
1
Set up Flask app and upload folder
Create a Flask app by importing Flask and instantiating app = Flask(__name__). Then create a variable called UPLOAD_FOLDER and set it to the string 'uploads/'.
Flask
Need a hint?

Remember to import Flask and create the app instance. The upload folder is just a string variable.

2
Create the HTML upload form route
Add a route @app.route('/') with a function called upload_form that returns a string with an HTML form. The form must have method='POST', enctype='multipart/form-data', and a file input with name='file'. Also include a submit button.
Flask
Need a hint?

The form must use POST and multipart encoding to send files. The input's name must be exactly 'file'.

3
Add POST route to handle file upload
Modify the @app.route('/') decorator to accept both GET and POST methods. Inside upload_form, check if the request method is POST. If yes, get the uploaded file from request.files['file']. Then save the file to UPLOAD_FOLDER using file.save(). Import request from flask.
Flask
Need a hint?

Use methods=['GET', 'POST'] in the route decorator. Use request.files['file'] to get the uploaded file.

4
Add app run command
Add the standard Flask app run block at the end: if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Need a hint?

This block runs the Flask app when you start the script. Use debug=True for easier testing.