Handling File Uploads in Flask
Key Concepts
- File Upload Form
- File Storage
- File Validation
- File Handling in Flask
File Upload Form
To handle file uploads in Flask, you need to create an HTML form that allows users to select and upload files. The form must have the enctype="multipart/form-data"
attribute to ensure that the file data is sent correctly.
<form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form>
File Storage
Once a file is uploaded, it needs to be stored on the server. Flask provides a simple way to handle this using the request.files
object. You can save the file to a specific directory on the server.
from flask import Flask, request, redirect, url_for import os app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads/' @app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) return redirect(url_for('uploaded_file', filename=file.filename))
File Validation
It's important to validate the uploaded file to ensure it meets your requirements. For example, you can check the file type, size, and other attributes before saving it.
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] if file and allowed_file(file.filename): file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) return redirect(url_for('uploaded_file', filename=file.filename)) else: return "Invalid file type"
File Handling in Flask
Flask provides various methods to handle uploaded files. You can read the file content, process it, and even serve it back to the user. The send_from_directory
function can be used to serve uploaded files.
from flask import send_from_directory @app.route('/uploads/') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename)