| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- from fastapi import APIRouter, HTTPException, UploadFile, File
- from fastapi.responses import JSONResponse
- import aiofiles
- from pathlib import Path
- import aiofiles.os as aios
- from typing import Optional
- import platform
- from utils.logu import get_logger
- from utils.config import OUTPUT_DIR
- import os
- import uuid
- router = APIRouter(prefix="/file")
- logger = get_logger("FileRouter")
- from fastapi.concurrency import run_in_threadpool
- # 确保上传目录存在
- UPLOAD_DIR = OUTPUT_DIR / "upload"
- UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
- @router.post("/upload", tags=["file"])
- async def upload_file(file: UploadFile = File(...)):
- """处理文件上传"""
- try:
- file_path = UPLOAD_DIR / file.filename
-
- # 异步写入文件
- async with aiofiles.open(file_path, "wb") as f:
- while chunk := await file.read(1024 * 1024): # 1MB chunks
- await f.write(chunk)
-
- return {
- "filename": file.filename,
- "saved_path": str(file_path),
- "size": file_path.stat().st_size
- }
- except Exception as e:
- logger.error(f"文件上传失败: {str(e)}")
- raise HTTPException(status_code=500, detail=str(e))
- @router.get("/list", tags=["file"])
- async def list_files(path: str):
- """列出目录下的文件"""
-
|