downloader.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. method: 'GET',
  29. ...config,
  30. responseType: 'blob',
  31. };
  32. const response = await this.client.request<T>(url, finalConfig);
  33. return response;
  34. }
  35. }
  36. export { FileDownloader };