36 lines
1.0 KiB
Python
36 lines
1.0 KiB
Python
|
|
# app/api/routes/uploads.py
|
|||
|
|
from fastapi import APIRouter, UploadFile, File, HTTPException, Request
|
|||
|
|
from uuid import uuid4
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
router = APIRouter(tags=["uploads"])
|
|||
|
|
|
|||
|
|
# 保存目录:项目根目录下 static/uploads
|
|||
|
|
UPLOAD_DIR = Path("static/uploads")
|
|||
|
|
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/upload-image")
|
|||
|
|
async def upload_image(
|
|||
|
|
request: Request,
|
|||
|
|
file: UploadFile = File(...),
|
|||
|
|
):
|
|||
|
|
# 只允许图片
|
|||
|
|
if not file.content_type.startswith("image/"):
|
|||
|
|
raise HTTPException(status_code=400, detail="只支持图片上传")
|
|||
|
|
|
|||
|
|
# 生成文件名
|
|||
|
|
ext = (file.filename or "").rsplit(".", 1)[-1].lower() or "png"
|
|||
|
|
name = f"{uuid4().hex}.{ext}"
|
|||
|
|
save_path = UPLOAD_DIR / name
|
|||
|
|
|
|||
|
|
# 保存文件
|
|||
|
|
content = await file.read()
|
|||
|
|
save_path.write_bytes(content)
|
|||
|
|
|
|||
|
|
# 拼出完整 URL,确保在 3000 端口页面里也能访问到 8000 的静态资源
|
|||
|
|
base = str(request.base_url).rstrip("/") # e.g. "http://127.0.0.1:8000"
|
|||
|
|
url = f"{base}/static/uploads/{name}"
|
|||
|
|
|
|||
|
|
return {"url": url}
|