hku-class/backend/app/api/upload.py
2026-04-27 09:21:20 +08:00

25 lines
936 B
Python

from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from app.core.deps import require_role
from app.db.models import User
from app.services.cos_service import upload_image
router = APIRouter(prefix="/api/upload", tags=["upload"])
@router.post("/image")
async def upload_image_api(
file: UploadFile = File(...),
user: User = Depends(require_role("super_admin", "teacher", "student")),
):
"""Upload an image to Tencent COS."""
contents = await file.read()
if len(contents) > 10 * 1024 * 1024: # 10MB
raise HTTPException(status_code=400, detail="File too large (max 10MB)")
if file.content_type not in {"image/jpeg", "image/png", "image/gif", "image/webp"}:
raise HTTPException(status_code=400, detail="Invalid file type, only JPEG/PNG/GIF/WebP allowed")
url = upload_image("images", file.filename or "upload.jpg", contents, file.content_type)
return {"url": url}