Files
chat/backend/app/routers/uploads.py
T
2026-06-12 23:14:12 +08:00

64 lines
1.9 KiB
Python

"""文件上传路由"""
import os
import uuid
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from app.config import settings
from app.dependencies import get_current_user
from app.models.user import User
router = APIRouter()
@router.post("/avatar")
async def upload_avatar(
file: UploadFile = File(...),
user: User = Depends(get_current_user),
):
"""上传头像"""
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="只能上传图片文件")
# 检查文件大小
contents = await file.read()
max_size = settings.MAX_UPLOAD_SIZE_MB * 1024 * 1024
if len(contents) > max_size:
raise HTTPException(status_code=400, detail=f"文件大小超过 {settings.MAX_UPLOAD_SIZE_MB}MB")
# 保存文件
ext = os.path.splitext(file.filename or "image.jpg")[1]
filename = f"avatar_{user.id}{ext}"
filepath = os.path.join(settings.UPLOAD_DIR, filename)
with open(filepath, "wb") as f:
f.write(contents)
return {"url": f"/uploads/{filename}"}
@router.post("/file")
async def upload_file(
file: UploadFile = File(...),
user: User = Depends(get_current_user),
):
"""上传文件(聊天中使用)"""
contents = await file.read()
max_size = settings.MAX_UPLOAD_SIZE_MB * 1024 * 1024
if len(contents) > max_size:
raise HTTPException(status_code=400, detail=f"文件大小超过 {settings.MAX_UPLOAD_SIZE_MB}MB")
ext = os.path.splitext(file.filename or "file")[1]
filename = f"{uuid.uuid4().hex}{ext}"
filepath = os.path.join(settings.UPLOAD_DIR, filename)
with open(filepath, "wb") as f:
f.write(contents)
return {
"url": f"/uploads/{filename}",
"filename": file.filename,
"size": len(contents),
"content_type": file.content_type,
}