"""手动上传图片:插件用户在采集区手动补充参考图,转存本地 media 供预览与生图。""" from __future__ import annotations from fastapi import APIRouter, File, HTTPException, UploadFile from services import storage router = APIRouter(prefix="/api", tags=["upload"]) # content-type → 落盘扩展名 _ALLOWED_TYPES = { "image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp", "image/gif": ".gif", } MAX_BYTES = 20 * 1024 * 1024 # 20MB @router.post("/upload-image") async def upload_image(file: UploadFile = File(...)): data = await file.read() ctype = (file.content_type or "").split(";")[0].strip().lower() if ctype not in _ALLOWED_TYPES: raise HTTPException(status_code=400, detail=f"不支持的图片类型: {file.content_type}") if not data: raise HTTPException(status_code=400, detail="空文件") if len(data) > MAX_BYTES: raise HTTPException(status_code=400, detail="图片超过 20MB") key = storage.write_bytes(data, key_prefix="uploads", ext=_ALLOWED_TYPES[ctype]) return {"url": storage.public_url(key), "key": key}