How to Get Uploaded File in Flask: Simple Guide
In Flask, you get an uploaded file using
request.files inside your route function. Access the file by its form field name, for example, file = request.files['file'], then you can save or process it.Syntax
Use request.files to access files sent by the client in a POST request. The key inside request.files matches the name attribute of the file input in the HTML form.
request.files['file']: gets the uploaded file object.file.filename: the original filename on the client.file.save(path): saves the file to the server.
python
from flask import request @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] # 'file' is the input field name filename = file.filename file.save(f'/path/to/save/{filename}') return 'File uploaded successfully'
Example
This example shows a simple Flask app with an HTML form to upload a file. The server receives the file and saves it to a folder named uploads.
python
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('/') def index(): return render_template_string(''' <form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ''') @app.route('/upload', methods=['POST']) def upload(): file = request.files.get('file') if file and file.filename: filepath = os.path.join(UPLOAD_FOLDER, file.filename) file.save(filepath) return f'File "{file.filename}" uploaded successfully.' return 'No file selected or empty filename.' if __name__ == '__main__': app.run(debug=True)
Output
Running the app and uploading a file shows: File "example.txt" uploaded successfully.
Common Pitfalls
- Not setting
enctype="multipart/form-data"in the HTML form causesrequest.filesto be empty. - Using
request.forminstead ofrequest.filesto get files will not work. - Trying to access a file key that does not exist raises a
KeyError. Userequest.files.get('file')to avoid this. - Not checking if
file.filenameis empty can cause saving empty files.
python
from flask import request # Wrong way (missing enctype and wrong access) # HTML form without enctype="multipart/form-data" will not send files properly. # Right way file = request.files.get('file') if file and file.filename: file.save('/path/to/save/' + file.filename)
Quick Reference
Remember these key points when handling file uploads in Flask:
- Use
request.files['fieldname']to get the file. - Set
enctype="multipart/form-data"in your HTML form. - Check if the file exists and has a filename before saving.
- Save files securely to avoid overwriting or security risks.
Key Takeaways
Use request.files with the form input name to get uploaded files in Flask.
Always set enctype="multipart/form-data" in your HTML form for file uploads.
Check if the file exists and has a valid filename before saving.
Use file.save(path) to store the uploaded file on the server.
Use request.files.get() to avoid errors if the file key is missing.