import os import uuid from fastapi import APIRouter, File, HTTPException, UploadFile from app.config import UPLOAD_DIR router = APIRouter(tags=["media"]) ALLOWED_EXT = {".jpg", ".jpeg", ".png", ".webp", ".gif"} @router.post("/upload") async def upload_file(file: UploadFile = File(...)): ext = os.path.splitext(file.filename or "")[-1].lower() if ext not in ALLOWED_EXT: raise HTTPException(status_code=400, detail="Format non supporté") filename = f"{uuid.uuid4().hex}{ext}" dest = os.path.join(UPLOAD_DIR, filename) os.makedirs(UPLOAD_DIR, exist_ok=True) content = await file.read() with open(dest, "wb") as f: f.write(content) return {"filename": filename, "url": f"/uploads/{filename}"} @router.delete("/upload/{filename}", status_code=204) def delete_file(filename: str): path = os.path.join(UPLOAD_DIR, filename) if os.path.exists(path): os.remove(path)