Welcome to our comprehensive guide on File Validation using Flask! In this tutorial, we'll learn how to handle file uploads and validate them for various types and sizes. Let's dive in! 🎯
In web development, file uploads are an essential part of many applications. Flask provides an easy way to handle file uploads through forms. However, it's crucial to validate these files to ensure they are of the expected type and size.
Before we begin, let's set up a basic Flask application.
from flask import Flask, request, render_template, redirect, url_for
app = Flask(__name__)
app.config['UPLOADED_FILE_DIR'] = 'uploads/'In this example, we've imported the necessary Flask modules and created a Flask web application named app. We've also set up a directory for uploaded files.
Now let's create a simple HTML form for file uploading.
<form action="{{ url_for('upload_file') }}" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload File">
</form>In the Flask app, we'll create a route to handle the file upload.
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOADED_FILE_DIR'], filename))
return redirect(url_for('success'))
else:
return "Invalid file uploaded"
return render_template('upload.html')In this code, we've created a route named upload that handles both GET and POST requests. If it's a POST request, we're checking if a file was uploaded, and if it's a valid file (using the allowed_file function, which we'll define later). If the file is valid, we're saving it to the UPLOADED_FILE_DIR and redirecting to a success page.
To validate file types, we'll create a helper function:
import mimetypes
def allowed_file(filename):
allowed_mime_types = ['application/octet-stream', 'image/jpeg', 'image/png', 'image/gif', 'application/pdf']
mime_type = mimetypes.guess_type(filename)[0]
return mime_type in allowed_mime_typesIn this function, we're using the mimetypes module to guess the MIME type of the uploaded file and checking if it's one of the allowed types.
To validate file size, we can use Python's built-in os module:
import os
def max_size(size_in_MB=5):
return size_in_MB * (1024 ** 2)
def secure_filename(filename):
import os
import re
from urllib.parse import unquote
filename = unquote(filename)
filename = re.sub(r'[^\w.\s]', '', filename)
return f'{os.path.splitext(filename)[0].replace(" ", "_")}.{os.path.splitext(filename)[1]}'
def allowed_size(filename):
allowed_extensions = ['jpeg', 'png', 'gif', 'pdf']
filename, ext = os.path.splitext(filename)
if ext not in allowed_extensions:
return False
size = os.path.getsize(os.path.join(app.config['UPLOADED_FILE_DIR'], filename))
if size > max_size():
return False
return TrueIn this code, we've defined a function max_size to set the maximum file size (in MB). We've also modified the secure_filename function to handle spaces in filenames and defined a new function allowed_size to check if the file size is within the allowed limit.
Which function is used to guess the MIME type of an uploaded file?
What does the `secure_filename` function do?
That's it for this tutorial! In the next tutorial, we'll explore more advanced topics like handling multiple file uploads and working with forms. Happy coding! 🎯