DocHub/backend/app/routers/files.py

27 lines
777 B
Python

import mimetypes
from pathlib import Path
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from app.config import settings
router = APIRouter()
def _resolve_safe(key: str) -> Path:
base = Path(settings.storage_dir).resolve()
path = (base / key).resolve()
if not path.is_relative_to(base):
raise HTTPException(status_code=400, detail="Invalid path")
return path
@router.get("/api/files/{key:path}")
def serve_file(key: str):
path = _resolve_safe(key)
if not path.exists() or not path.is_file():
raise HTTPException(status_code=404, detail="File not found")
media_type, _ = mimetypes.guess_type(str(path))
return FileResponse(path, media_type=media_type or "application/octet-stream")