Validate uploaded files for MIME type and size, then save with a UUID filename in FastAPI.
File Uploads in FastAPI
from fastapi import File, UploadFile, HTTPException
import uuid, os
ALLOWED = {"image/jpeg", "image/png", "image/webp"}
MAX_MB = 10 * 1024 * 1024 # 10 MB
@app.post("/upload", status_code=201)
async def upload_file(file: UploadFile = File(...)):
if file.content_type not in ALLOWED:
raise HTTPException(400, "File type not allowed")
content = await file.read()
if len(content) > MAX_MB:
raise HTTPException(413, "File too large")
ext = os.path.splitext(file.filename)[1].lower()
filename = uuid.uuid4().hex + ext
with open("uploads/" + filename, "wb") as f:
f.write(content)
return {"filename": filename, "size": len(content)}
# Multiple files
@app.post("/upload-many")
async def upload_many(files: list[UploadFile] = File(...)):
results = []
for file in files:
data = await file.read()
results.append({"name": file.filename, "size": len(data)})
return results