file.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from fastapi import APIRouter, HTTPException
  2. from fastapi.responses import FileResponse
  3. import os
  4. from setting import UPLOAD_DIR, OUTPUT_DIR
  5. router = APIRouter(prefix="/api1/file", tags=["file"])
  6. @router.get("/image/{filename}")
  7. async def get_image(filename: str):
  8. # 1. 构建完整路径
  9. file_path = os.path.join(UPLOAD_DIR, filename)
  10. return get_file(file_path)
  11. #
  12. # # 2. 安全检查:防止目录穿越漏洞 (Directory Traversal)
  13. # # 确保用户请求的文件确实在 UPLOAD_DIR 目录下
  14. # real_path = os.path.realpath(file_path)
  15. # if not real_path.startswith(os.path.realpath(UPLOAD_DIR)):
  16. # raise HTTPException(status_code=403, detail="拒绝访问该路径")
  17. #
  18. # # 3. 检查文件是否存在
  19. # if not os.path.exists(real_path):
  20. # raise HTTPException(status_code=404, detail="图片不存在")
  21. #
  22. # # 4. 返回文件流
  23. # # media_type 会根据后缀自动识别(如 image/jpeg),也可以手动指定
  24. # return FileResponse(real_path)
  25. @router.get("/audio/{filename}")
  26. async def get_audio(filename: str):
  27. # 1. 构建完整路径
  28. file_path = os.path.join(UPLOAD_DIR, filename)
  29. return get_file(file_path)
  30. @router.get("/video/{filename}")
  31. async def get_video(filename: str):
  32. # 1. 构建完整路径
  33. file_path = os.path.join(OUTPUT_DIR, filename)
  34. return get_file(file_path)
  35. def get_file(file_path):
  36. # 2. 安全检查:防止目录穿越漏洞 (Directory Traversal)
  37. # 确保用户请求的文件确实在 UPLOAD_DIR 目录下
  38. real_path = os.path.realpath(file_path)
  39. if not (real_path.startswith(os.path.realpath(UPLOAD_DIR)) or real_path.startswith(os.path.realpath(OUTPUT_DIR))):
  40. raise HTTPException(status_code=403, detail="拒绝访问该路径")
  41. # 3. 检查文件是否存在
  42. if not os.path.exists(real_path):
  43. raise HTTPException(status_code=404, detail="视频不存在")
  44. # 4. 返回文件流
  45. # media_type 会根据后缀自动识别(如 image/jpeg),也可以手动指定
  46. return FileResponse(real_path)