Fullstack Flask: Handling File Uploads and Downloads via APIs
In modern web applications, file uploads and downloads are common functionalities—whether for profile image uploads, document management, or downloading reports. Flask, a lightweight Python web framework, provides excellent support for building RESTful APIs that handle these operations smoothly. This blog explains how to implement file uploads and downloads in a fullstack Flask application using simple and secure approaches.
Setting Up the Flask Environment
To begin, ensure you have Flask installed:
bash
pip install Flask
Create a basic Flask app structure with the necessary folders:
project/
├── app.py
├── uploads/
└── downloads/
The uploads folder will store uploaded files, and the downloads folder can contain files available for users to download.
Implementing File Upload API
Flask simplifies file handling using request.files. Below is an API route to upload files:
python
from flask import Flask, request, jsonify
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No selected file'}), 400
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filepath)
return jsonify({'message': f'File {file.filename} uploaded successfully'}), 200
Ensure the upload folder exists or create it dynamically using os.makedirs.
Implementing File Download API
Downloading files requires a route that returns a file from the server using Flask’s send_from_directory() function.
python
Copy
Edit
from flask import send_from_directory
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
return send_from_directory('downloads', filename, as_attachment=True)
This method securely sends files and prompts users to download them instead of displaying them in the browser.
Handling Security and Validations
Always sanitize filenames before saving them to avoid path traversal attacks. Use werkzeug.utils.secure_filename:
python
Copy
Edit
from werkzeug.utils import secure_filename
filename = secure_filename(file.filename)
Also, consider restricting file types to prevent malicious uploads:
python
Copy
Edit
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
Then update the upload route:
python
Copy
Edit
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
Integrating With Frontend
In a fullstack app, frontend frameworks like React or Angular can use fetch or axios to send FormData to the Flask backend for uploads. For downloads, a simple <a href="API_URL/download/filename">Download</a> link will suffice.
Conclusion
Handling file uploads and downloads in Flask is efficient and flexible. By using built-in utilities like request.files, secure_filename, and send_from_directory, you can implement secure file handling APIs. When integrated with a frontend framework, this forms a powerful part of your fullstack development toolkit. Always remember to validate files and implement security best practices to keep your application robust and safe.
Learn FullStack Python Training Course
Read More : Implementing Rate Limiting in Flask APIs with Flask-Limiter
Visit Quality Thought Training Institute Hyderabad
Get Direction
Comments
Post a Comment