File size limits help keep your app safe and fast by stopping users from uploading very large files.
0
0
File size limits in Flask
Introduction
When you want to stop users from uploading files bigger than a certain size.
When you want to save server space and avoid slow uploads.
When you want to protect your app from accidental or harmful large files.
When you want to give users clear feedback if their file is too big.
Syntax
Flask
app.config['MAX_CONTENT_LENGTH'] = size_in_bytesSet MAX_CONTENT_LENGTH in your Flask app config to limit upload size.
The size is in bytes. For example, 1 MB = 1_000_000 bytes.
Examples
This sets the max upload size to 1 megabyte.
Flask
app.config['MAX_CONTENT_LENGTH'] = 1_000_000 # 1 MB limit
This sets the max upload size to 5 megabytes using multiplication for clarity.
Flask
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024 # 5 MB limit
Sample Program
This Flask app limits file uploads to 2 MB. If a user tries to upload a bigger file, Flask stops the request and returns an error automatically.
Flask
from flask import Flask, request, abort app = Flask(__name__) # Limit uploads to 2 MB app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024 @app.route('/upload', methods=['POST']) def upload_file(): file = request.files.get('file') if not file: return 'No file uploaded', 400 # If file is too large, Flask automatically aborts with 413 error return f'File {file.filename} uploaded successfully!' if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Flask returns a 413 error if the file is too big. You can customize this error by adding an error handler for 413.
Remember to set MAX_CONTENT_LENGTH before running your app.
This limit applies to the whole request size, including all form data.
Summary
Set MAX_CONTENT_LENGTH in Flask config to limit file upload size.
Limits help protect your app and improve user experience.
Flask automatically stops requests that exceed the limit with a 413 error.