FastAPI File Upload with Size Limit
Handle file uploads in FastAPI with UploadFile, enforce file size limits, validate MIME types, and save to disk with unique filenames. Includes async.
Code
from fastapi import FastAPI, UploadFile, File, HTTPException
import uuid, os
app = FastAPI()
MAX_SIZE = 10 * 1024 * 1024 # 10MB
ALLOWED_TYPES = {'image/jpeg', 'image/png', 'application/pdf'}
@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
if file.content_type not in ALLOWED_TYPES:
raise HTTPException(400, 'File type not allowed')
contents = await file.read()
if len(contents) > MAX_SIZE:
raise HTTPException(413, 'File too large')
filename = f'{uuid.uuid4()}.{file.filename.split(".")[-1]}'
with open(f'uploads/{filename}', 'wb') as f:
f.write(contents)
return {'filename': filename, 'size': len(contents)}