Fullstack Flask: Handling File Uploads and Downloads via APIs
In modern web applications, file upload and download functionalities are essential—whether you're building a document management system, image-sharing platform, or a backend for mobile apps. Flask, a lightweight Python web framework, offers simple yet powerful tools to handle these operations securely through REST APIs. In this blog, we’ll walk through how to implement file uploads and downloads in a fullstack Flask application.
Why Handle File Uploads and Downloads via APIs?
APIs allow frontend and mobile applications to interact with your Flask backend, making file transfer operations seamless across platforms. Using RESTful endpoints, files can be stored on the server, retrieved by clients, and even integrated with cloud storage solutions if needed.
Setting Up Your Flask App
Before diving into the code, ensure Flask is installed:
bash
pip install Flask
Create a basic Flask app structure:
bash
/app
├── uploads/
├── app.py
Handling File Uploads
Let’s create an API endpoint to upload files. Flask provides a request.files object to work with uploaded files.
python
from flask import Flask, request, jsonify
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'No file part in the request'}), 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': 'File uploaded successfully', 'filename': file.filename}), 200
Tips for production:
Validate file extensions (.pdf, .jpg, etc.)
Rename files to avoid collisions
Store metadata in a database
Handling File Downloads
To allow users to download files, use 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):
try:
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
except FileNotFoundError:
return jsonify({'error': 'File not found'}), 404
Now, users can access /download/sample.pdf to download files previously uploaded.
Frontend or API Client Example
A simple cURL command to upload a file:
bash
Copy
Edit
curl -X POST -F "file=@sample.pdf" http://localhost:5000/upload
To download a file:
bash
Copy
Edit
curl -O http://localhost:5000/download/sample.pdf
You can also integrate this with frontend frameworks (React, Vue) using Axios or fetch() for smoother user interaction.
Security Best Practices
File validation: Only accept specific file types.
Sanitize filenames: Use Python’s secure_filename() from werkzeug.utils.
Limit file size: Prevent denial-of-service attacks by restricting file size using MAX_CONTENT_LENGTH.
Authentication: Protect file endpoints using JWT or session-based auth.
Conclusion
Handling file uploads and downloads via APIs in Flask is straightforward but must be done carefully to ensure security, scalability, and usability. By creating RESTful endpoints and adding proper validation, you can build reliable file-handling features in any fullstack application. Whether you're working with images, documents, or multimedia files, Flask gives you the flexibility and control to manage file transfers efficiently.
Learn FullStack Python Training Course
Read More : Building CRUD APIs with Flask and SQLAlchemy
Read More : Flask and OpenAPI: Designing APIs with Swagger for Fullstack Applications
Read More : Fullstack Python: Implementing GraphQL APIs in Flask
Visit Quality Thought Training Institute
Comments
Post a Comment