useDownload.ts 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. };
  44. /**
  45. * @description 接收数据流生成 blob,创建链接,下载文件, 非api
  46. * @param {any} t i18n
  47. * @param {any} data 导出的内容
  48. * @param {String} tempName 导出的文件名 (必传)
  49. * @param {Object} blobParams 导出的blob参数 (默认{})
  50. * @param {String} fileType 导出的文件格式 (默认为.xlsx)
  51. * */
  52. export const useDownloadLocal = (t: any, data: any, tempName: string, blobParams: Object = {}, fileType: string = ".xlsx") => {
  53. try {
  54. let fileName = tempName + fileType;
  55. const blob = new Blob([data], blobParams);
  56. // 兼容 edge 不支持 createObjectURL 方法
  57. if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, fileName);
  58. const blobUrl = window.URL.createObjectURL(blob);
  59. const exportFile = document.createElement("a");
  60. exportFile.style.display = "none";
  61. exportFile.download = fileName;
  62. exportFile.href = blobUrl;
  63. document.body.appendChild(exportFile);
  64. exportFile.click();
  65. // 去除下载对 url 的影响
  66. document.body.removeChild(exportFile);
  67. window.URL.revokeObjectURL(blobUrl);
  68. ElNotification({
  69. title: t("sys.app.logoutTip"),
  70. message: `${t("sys.api.exportSyccess")}:${fileName}`,
  71. type: "success",
  72. duration: 3000
  73. });
  74. } catch (error) {
  75. console.log(error);
  76. }
  77. };