AI generated a FastAPI endpoint for avatar uploads.
Python backend with local file storage behind Nginx.
Select suspicious lines in the terminal to flag them before submitting your verdict.
from fastapi import APIRouter, UploadFile, File, HTTPException
from pathlib import Path
import uuid
import imghdr
router = APIRouter()
ALLOWED_TYPES = {"image/jpeg", "image/png", "image/webp"}
MAX_SIZE = 2 * 1024 * 1024
@router.post("/upload-avatar")
async def upload_avatar(file: UploadFile = File(...)):
if file.content_type not in ALLOWED_TYPES:
raise HTTPException(400, "Invalid file type")
data = await file.read()
if len(data) > MAX_SIZE:
raise HTTPException(400, "File too large")
ext = Path(file.filename).suffix.lower()
if ext not in {".jpg", ".jpeg", ".png", ".webp"}:
raise HTTPException(400, "Invalid extension")
kind = imghdr.what(None, h=data)
if kind not in {"jpeg", "png", "webp"}:
raise HTTPException(400, "Invalid image content")
dest = Path("/var/uploads/avatars") / f"{uuid.uuid4()}{ext}"
dest.write_bytes(data)
return {"url": f"/static/avatars/{dest.name}"}