file.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from fastapi import APIRouter, HTTPException, UploadFile, File
  2. from fastapi.responses import JSONResponse
  3. import aiofiles
  4. from pathlib import Path
  5. import aiofiles.os as aios
  6. from typing import Optional
  7. import platform
  8. from utils.logu import get_logger
  9. from utils.config import OUTPUT_DIR
  10. import os
  11. import uuid
  12. router = APIRouter(prefix="/file")
  13. logger = get_logger("FileRouter")
  14. from fastapi.concurrency import run_in_threadpool
  15. # 确保上传目录存在
  16. UPLOAD_DIR = OUTPUT_DIR / "upload"
  17. UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
  18. @router.post("/upload", tags=["file"])
  19. async def upload_file(file: UploadFile = File(...)):
  20. """处理文件上传"""
  21. try:
  22. file_path = UPLOAD_DIR / file.filename
  23. # 异步写入文件
  24. async with aiofiles.open(file_path, "wb") as f:
  25. while chunk := await file.read(1024 * 1024): # 1MB chunks
  26. await f.write(chunk)
  27. return {
  28. "filename": file.filename,
  29. "saved_path": str(file_path),
  30. "size": file_path.stat().st_size
  31. }
  32. except Exception as e:
  33. logger.error(f"文件上传失败: {str(e)}")
  34. raise HTTPException(status_code=500, detail=str(e))
  35. @router.get("/list", tags=["file"])
  36. async def list_files(path: str):
  37. """列出目录下的文件"""