0
0
Flaskframework~30 mins

File uploads handling in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
File uploads handling
📖 Scenario: You are building a simple web app where users can upload images to share with friends.This app needs a form to select a file and a server route to receive and save the uploaded file.
🎯 Goal: Create a Flask app that accepts image file uploads from users and saves them on the server.
📋 What You'll Learn
Create a Flask app with a route to show an upload form
Add a route to handle POST requests with file uploads
Save the uploaded file to a folder named uploads
Use secure filename handling to avoid unsafe file names
💡 Why This Matters
🌍 Real World
File uploads are common in web apps for profile pictures, documents, or media sharing.
💼 Career
Understanding file upload handling is essential for backend web developers working with user-generated content.
Progress0 / 4 steps
1
Set up Flask app and upload folder
Import Flask and request from flask. Create a Flask app called app. Define a variable UPLOAD_FOLDER and set it to 'uploads'.
Flask
Need a hint?

Start by importing Flask and request, then create the app and set the upload folder path.

2
Create upload form route
Add a route /upload that responds to GET requests. Inside the function upload_form, return a simple HTML form string with method='POST' and enctype='multipart/form-data'. The form should have an input of type file with name='file' and a submit button.
Flask
Need a hint?

Use @app.route with methods=['GET'] and return a form with file input and submit button.

3
Add POST route to handle file upload
Modify the /upload route to accept POST requests. Inside the function upload_file, check if 'file' is in request.files. If yes, get the file object from request.files['file']. Import secure_filename from werkzeug.utils and use it to get a safe filename. Save the file to UPLOAD_FOLDER using file.save(). Return a success message string.
Flask
Need a hint?

Change the route to accept POST. Use request.files to get the file, secure the filename, and save it.

4
Ensure upload folder exists and run app
Import os. Before running the app, check if the folder UPLOAD_FOLDER exists using os.path.exists(). If not, create it with os.makedirs(). Add the if __name__ == '__main__': block and run the app with app.run(debug=True).
Flask
Need a hint?

Check if the upload folder exists and create it if missing. Then add the main block to run the app.