Saving uploaded files lets your web app keep files users send, like photos or documents. This helps you use or share those files later.
Saving uploaded files in Flask
Introduction
Syntax
Flask
from flask import request file = request.files['file'] file.save('/path/to/save/filename')
Use
request.files to get the uploaded file from the form.Call
save() on the file object with the path where you want to store it.Examples
Flask
file = request.files['photo'] file.save('uploads/profile.jpg')
Flask
uploaded_file = request.files.get('document') if uploaded_file: uploaded_file.save(f"uploads/{uploaded_file.filename}")
Sample Program
This Flask app shows a simple form to upload a file. When a file is sent, it saves it in the 'uploads' folder and confirms the filename saved.
Flask
from flask import Flask, request, render_template_string import os app = Flask(__name__) UPLOAD_FOLDER = 'uploads' os.makedirs(UPLOAD_FOLDER, exist_ok=True) @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files.get('file') if file: save_path = os.path.join(UPLOAD_FOLDER, file.filename) file.save(save_path) return f'File saved as {file.filename}' return 'No file uploaded' return render_template_string(''' <form method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ''') if __name__ == '__main__': app.run(debug=True)
Important Notes
Always check if the file exists before saving to avoid errors.
Use secure filenames to avoid security risks (Flask has werkzeug.utils.secure_filename for this).
Make sure the folder where you save files exists and your app has permission to write there.
Summary
Use request.files to get uploaded files in Flask.
Call save() on the file object with a path to store it.
Check for file presence and use safe filenames to keep your app secure.
Practice
1. In Flask, which object do you use to access files uploaded by a user in a form?
easy
Solution
Step 1: Understand Flask request objects
Flask provides different objects to access data sent by the client.request.filesholds uploaded files.Step 2: Identify correct object for files
request.formis for form fields,request.datais raw data, andrequest.argsis for URL query parameters.Final Answer:
request.files-> Option BQuick Check:
Uploaded files = request.files [OK]
Hint: Uploaded files are always in request.files [OK]
Common Mistakes:
- Using request.form to get files
- Trying to access files from request.args
- Confusing request.data with files
2. Which of the following is the correct way to save an uploaded file named
file to a folder called uploads in Flask?easy
Solution
Step 1: Use the file object's save method
The uploaded file object has asave()method that takes the full path to save the file.Step 2: Provide correct path including folder and filename
Concatenate the folder path and the file's filename to save it in the right place.Final Answer:
file.save('uploads/' + file.filename) -> Option AQuick Check:
Use file.save(path) with full path [OK]
Hint: Use file.save('folder/' + file.filename) to save files [OK]
Common Mistakes:
- Calling save() without a path
- Using save() as a standalone function
- Not including folder path in save()
3. What will happen when this Flask code runs after a file upload?
file = request.files['photo']
file.save('/tmp/' + file.filename)
return 'Saved!'medium
Solution
Step 1: Access the uploaded file from request.files
The code gets the file named 'photo' from the uploaded files correctly.Step 2: Save the file to /tmp/ folder with original filename
Callingsave()with '/tmp/' + filename saves the file in that folder.Final Answer:
The uploaded file is saved in /tmp/ with its original filename and 'Saved!' is returned -> Option DQuick Check:
save() stores file at given path, returns confirmation [OK]
Hint: save() stores file at given path, returns confirmation [OK]
Common Mistakes:
- Assuming save() needs absolute path always
- Thinking request.files['photo'] is empty without upload
- Confusing save() behavior with form data saving
4. Identify the error in this Flask code snippet for saving an uploaded file:
file = request.files['file'] file.save(file.filename)
medium
Solution
Step 1: Check the save() method argument
The code saves the file using only the filename, without specifying a folder path.Step 2: Understand file saving location
Without a folder path, the file saves in the current working directory, which may be unintended or insecure.Final Answer:
Missing folder path in save() can cause files to save in wrong location -> Option AQuick Check:
Always include folder path in save() [OK]
Hint: Always include folder path in save() to control file location [OK]
Common Mistakes:
- Not specifying folder path in save()
- Confusing request.files with request.form
- Assuming file.filename is invalid
5. You want to securely save an uploaded file in Flask to the
uploads folder, avoiding unsafe filenames. Which code snippet correctly achieves this?from werkzeug.utils import secure_filename
file = request.files['file']
filename = secure_filename(file.filename)
file.save(f'uploads/{filename}')hard
Solution
Step 1: Use secure_filename to clean the filename
The functionsecure_filename()removes unsafe characters to prevent security issues.Step 2: Save the file with the cleaned filename in the uploads folder
Usingfile.save()with the cleaned filename inside the uploads folder saves the file securely.Final Answer:
This code safely saves the file with a cleaned filename in uploads folder -> Option CQuick Check:
Use secure_filename() before saving uploaded files [OK]
Hint: Use secure_filename() to avoid unsafe file names [OK]
Common Mistakes:
- Skipping secure_filename and risking unsafe filenames
- Assuming save() cleans filenames automatically
- Not creating uploads folder before saving
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
