We check file types to make sure users upload only safe and expected files. This helps keep the app secure and working well.
0
0
Allowed file types validation in Flask
Introduction
When users upload profile pictures and you want only images.
When accepting documents and you want to allow only PDFs or Word files.
When uploading audio or video files and you want to restrict formats.
When preventing harmful files like scripts or executables from being uploaded.
Syntax
Flask
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONSThe function checks if the file has an extension and if it is in the allowed list.
Use lower() to make the check case-insensitive.
Examples
This example allows only PDF and DOCX files.
Flask
ALLOWED_EXTENSIONS = {'pdf', 'docx'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONSThis example allows only MP3 and WAV audio files.
Flask
ALLOWED_EXTENSIONS = {'mp3', 'wav'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONSSample Program
This Flask app lets users upload files. It checks if the file type is allowed (only images). It shows a message if the file is accepted or rejected.
Flask
from flask import Flask, request, redirect, url_for, render_template_string app = Flask(__name__) ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def upload_file(): message = '' if request.method == 'POST': file = request.files.get('file') if file and allowed_file(file.filename): message = f"File '{file.filename}' is allowed and uploaded successfully." else: message = "File type not allowed. Please upload an image file." return render_template_string(''' <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Upload File</title> </head> <body> <h1>Upload an Image File</h1> <form method="post" enctype="multipart/form-data"> <input type="file" name="file" aria-label="Choose file to upload"> <button type="submit">Upload</button> </form> <p>{{ message }}</p> </body> </html> ''', message=message) if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Always check file extensions on the server side, never trust client-side checks alone.
Consider also checking the file content type or scanning files for extra security.
Summary
Allowed file types validation helps keep uploads safe and expected.
Use a set of allowed extensions and check the file's extension before saving.
Combine this with other security checks for best protection.