How to Save Uploaded File in Flask: Simple Guide
In Flask, you save an uploaded file by accessing it from
request.files, then calling its save() method with a secure filename. Use werkzeug.utils.secure_filename() to avoid unsafe file names before saving to your desired folder.Syntax
To save an uploaded file in Flask, use the following pattern:
request.files['file_field_name']: Access the uploaded file from the form.secure_filename(filename): Clean the filename to prevent security risks.file.save(path): Save the file to the specified path on the server.
python
from flask import request from werkzeug.utils import secure_filename file = request.files['file'] filename = secure_filename(file.filename) file.save('/path/to/save/' + filename)
Example
This example shows a minimal Flask app that accepts a file upload via a form and saves it to a folder named uploads in the project directory.
python
from flask import Flask, request, render_template_string from werkzeug.utils import secure_filename 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': if 'file' not in request.files: return 'No file part in the request', 400 file = request.files['file'] if file.filename == '': return 'No selected file', 400 filename = secure_filename(file.filename) file.save(os.path.join(UPLOAD_FOLDER, filename)) return f'File saved as {filename}' 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)
Output
When running, the app shows a file upload form at http://localhost:5000/. After uploading a file, it saves to the 'uploads' folder and shows 'File saved as filename.ext'.
Common Pitfalls
Common mistakes when saving uploaded files in Flask include:
- Not using
secure_filename(), which can lead to security risks like directory traversal. - Forgetting to check if the file part exists in
request.files. - Not handling empty filenames, which means no file was selected.
- Saving files to a folder that does not exist or without proper write permissions.
python
from flask import request # Wrong way (unsafe filename, no checks) file = request.files['file'] file.save('/uploads/' + file.filename) # Unsafe and may cause errors # Right way from werkzeug.utils import secure_filename import os file = request.files.get('file') if file and file.filename: filename = secure_filename(file.filename) os.makedirs('uploads', exist_ok=True) file.save(os.path.join('uploads', filename))
Quick Reference
Tips for saving uploaded files in Flask:
- Always use
secure_filename()to sanitize filenames. - Check if the file exists in
request.filesbefore saving. - Verify the filename is not empty.
- Create the target folder if it does not exist.
- Set proper permissions on the upload folder.
Key Takeaways
Use request.files to get the uploaded file in Flask.
Always sanitize filenames with werkzeug.utils.secure_filename before saving.
Check for file presence and non-empty filename to avoid errors.
Ensure the upload directory exists and has write permissions.
Save files using the file object's save() method with a safe path.