downloader.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import type { RequestClient } from '../request-client';
  2. import type { RequestClientConfig } from '../types';
  3. type DownloadRequestConfig = {
  4. /**
  5. * 定义期望获得的数据类型。
  6. * raw: 原始的AxiosResponse,包括headers、status等。
  7. * body: 只返回响应数据的BODY部分(Blob)
  8. */
  9. responseReturn?: 'body' | 'raw';
  10. } & Omit<RequestClientConfig, 'responseReturn'>;
  11. class FileDownloader {
  12. private client: RequestClient;
  13. constructor(client: RequestClient) {
  14. this.client = client;
  15. }
  16. /**
  17. * 下载文件
  18. * @param url 文件的完整链接
  19. * @param config 配置信息,可选。
  20. * @returns 如果config.responseReturn为'body',则返回Blob(默认),否则返回RequestResponse<Blob>
  21. */
  22. public async download<T = Blob>(
  23. url: string,
  24. config?: DownloadRequestConfig,
  25. ): Promise<T> {
  26. const finalConfig: DownloadRequestConfig = {
  27. responseReturn: 'body',
  28. ...config,
  29. responseType: 'blob',
  30. };
  31. const response = await this.client.get<T>(url, finalConfig);
  32. return response;
  33. }
  34. }
  35. export { FileDownloader };