37 行
1.2 KiB
Python
37 行
1.2 KiB
Python
from __future__ import annotations
|
|
import os
|
|
import uuid
|
|
|
|
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException
|
|
|
|
from app.auth import get_current_user
|
|
from app.config import settings
|
|
|
|
router = APIRouter(prefix="/api/upload", tags=["文件上传"], dependencies=[Depends(get_current_user)])
|
|
|
|
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
|
|
MAX_SIZE = 5 * 1024 * 1024 # 5MB
|
|
|
|
|
|
@router.post("/image", status_code=201)
|
|
async def upload_image(file: UploadFile = File(...), subdir: str = "uploads"):
|
|
ext = os.path.splitext(file.filename)[1].lower()
|
|
if ext not in ALLOWED_EXTENSIONS:
|
|
raise HTTPException(status_code=400, detail=f"不支持的文件格式: {ext}")
|
|
|
|
content = await file.read()
|
|
if len(content) > MAX_SIZE:
|
|
raise HTTPException(status_code=400, detail="文件大小不能超过5MB")
|
|
|
|
target_dir = os.path.join(settings.UPLOAD_DIR, subdir)
|
|
os.makedirs(target_dir, exist_ok=True)
|
|
|
|
filename = f"{uuid.uuid4().hex}{ext}"
|
|
filepath = os.path.join(target_dir, filename)
|
|
|
|
with open(filepath, "wb") as f:
|
|
f.write(content)
|
|
|
|
relative_path = f"/images/{subdir}/{filename}"
|
|
return {"url": relative_path, "filename": filename}
|