service.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. from typing import Dict
  3. from fastapi import UploadFile
  4. from app.core.exceptions import CustomException
  5. from app.core.base_schema import UploadResponseSchema, DownloadFileSchema
  6. from app.utils.upload_util import UploadUtil
  7. class FileService:
  8. """
  9. 文件管理服务层
  10. """
  11. @classmethod
  12. async def upload_service(cls, base_url: str, file: UploadFile, upload_type: str = 'local') -> Dict:
  13. """
  14. 上传文件。
  15. 参数:
  16. - base_url (str): 基础访问 URL。
  17. - file (UploadFile): 上传文件对象。
  18. - upload_type (str): 上传类型,'local' 或 'oss',默认 'local'。
  19. 返回:
  20. - Dict: 上传响应字典。
  21. 异常:
  22. - CustomException: 当未选择文件或上传类型错误时抛出。
  23. """
  24. if not file:
  25. raise CustomException(msg="请选择要上传的文件")
  26. if upload_type == 'local':
  27. filename, filepath, file_url = await UploadUtil.upload_file(file=file, base_url=base_url)
  28. else:
  29. raise CustomException(msg="上传类型错误")
  30. return UploadResponseSchema(
  31. file_path=f'{filepath}',
  32. file_name=filename,
  33. origin_name=file.filename,
  34. file_url=f'{file_url}',
  35. ).model_dump()
  36. @classmethod
  37. async def download_service(cls, file_path: str) -> DownloadFileSchema:
  38. """
  39. 下载文件。
  40. 参数:
  41. - file_path (str): 文件路径。
  42. 返回:
  43. - DownloadFileSchema: 下载文件响应对象。
  44. 异常:
  45. - CustomException: 当未选择文件或文件不存在时抛出。
  46. """
  47. if not file_path:
  48. raise CustomException(msg="请选择要下载的文件")
  49. if not UploadUtil.check_file_exists(file_path):
  50. raise CustomException(msg="文件不存在")
  51. file_name = UploadUtil.download_file(file_path)
  52. return DownloadFileSchema(
  53. file_path=file_path,
  54. file_name=str(file_name),
  55. )