useDownload.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { ElNotification } from "element-plus";
  2. /**
  3. * @description 接收数据流生成 blob,创建链接,下载文件
  4. * @param {Function} api 导出表格的api方法 (必传)
  5. * @param {String} tempName 导出的文件名 (必传)
  6. * @param {Object} params 导出的参数 (默认{})
  7. * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
  8. * @param {String} fileType 导出的文件格式 (默认为.xlsx)
  9. * */
  10. export const useDownload = async (
  11. api: (param: any) => Promise<any>,
  12. tempName: string,
  13. params: any = {},
  14. isNotify: boolean = true,
  15. fileType: string = ".xlsx"
  16. ) => {
  17. if (isNotify) {
  18. ElNotification({
  19. title: "温馨提示",
  20. message: "如果数据庞大会导致下载缓慢哦,请您耐心等待!",
  21. type: "info",
  22. duration: 3000
  23. });
  24. }
  25. try {
  26. const res = await api(params);
  27. const blob = new Blob([res]);
  28. // 兼容 edge 不支持 createObjectURL 方法
  29. if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, tempName + fileType);
  30. const blobUrl = window.URL.createObjectURL(blob);
  31. const exportFile = document.createElement("a");
  32. exportFile.style.display = "none";
  33. exportFile.download = `${tempName}${fileType}`;
  34. exportFile.href = blobUrl;
  35. document.body.appendChild(exportFile);
  36. exportFile.click();
  37. // 去除下载对 url 的影响
  38. document.body.removeChild(exportFile);
  39. window.URL.revokeObjectURL(blobUrl);
  40. } catch (error) {
  41. console.log(error);
  42. }
  43. };