0
0
Flaskframework~30 mins

Saving uploaded files in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Saving uploaded files
📖 Scenario: You are building a simple web app where users can upload a file. You want to save the uploaded file on the server so you can use it later.
🎯 Goal: Create a Flask app that accepts a file upload from a user and saves the file to a folder on the server.
📋 What You'll Learn
Create a Flask app with a route to upload files
Set a folder path to save uploaded files
Use Flask's request object to get the uploaded file
Save the uploaded file to the specified folder
💡 Why This Matters
🌍 Real World
Uploading and saving files is common in web apps for user profile pictures, documents, or media content.
💼 Career
Understanding file uploads is essential for backend web developers working with Flask or similar frameworks.
Progress0 / 4 steps
1
Set up Flask app and upload folder
Import Flask and request from flask. Create a Flask app called app. Set a variable UPLOAD_FOLDER to the string 'uploads/'.
Flask
Need a hint?

Use Flask(__name__) to create the app. Set UPLOAD_FOLDER as a string with the folder name.

2
Create upload route and HTML form
Add a route /upload to the app that accepts GET and POST methods. Inside the route function upload_file, if the request method is GET, return a simple HTML form string with a file input named file and a submit button.
Flask
Need a hint?

Use @app.route with methods=['GET', 'POST']. Return a form with enctype='multipart/form-data' and a file input named file.

3
Get uploaded file from request
Inside the upload_file function, after the GET block, add code for POST method. Get the uploaded file from request.files using the key 'file' and store it in a variable called uploaded_file.
Flask
Need a hint?

Use request.files['file'] to get the uploaded file object.

4
Save the uploaded file
Still inside the upload_file function, after getting uploaded_file, save it to the folder UPLOAD_FOLDER using the save() method. Use uploaded_file.filename to get the original filename. Return a string 'File saved successfully' after saving.
Flask
Need a hint?

Use uploaded_file.save() with the path combining UPLOAD_FOLDER and uploaded_file.filename. Return a success message string.