Files
video_detect/router/file_router.py

31 lines
1015 B
Python
Raw Normal View History

2025-09-30 17:17:20 +08:00
import os
from fastapi import FastAPI, HTTPException, Path, APIRouter
from fastapi.responses import FileResponse
from service.file_service import UPLOAD_ROOT
router = APIRouter(
prefix="/api/file",
tags=["文件管理"]
)
@router.get("/download/{relative_path:path}", summary="下载文件")
async def download_file(
relative_path: str = Path(..., description="文件的相对路径")
):
file_path = os.path.abspath(os.path.join(UPLOAD_ROOT, relative_path))
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail=f"文件不存在: {file_path}")
if not os.path.isfile(file_path):
raise HTTPException(status_code=400, detail="路径指向的不是文件")
if not file_path.startswith(os.path.abspath(UPLOAD_ROOT)):
raise HTTPException(status_code=403, detail="无权访问该文件")
return FileResponse(
path=file_path,
filename=os.path.basename(file_path),
media_type="application/octet-stream"
)