useMethods.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { defHttp } from '/@/utils/http/axios';
  2. import { useMessage } from '/@/hooks/web/useMessage';
  3. import { useGlobSetting } from '/@/hooks/setting';
  4. import { message } from 'ant-design-vue';
  5. const { createMessage, createWarningModal } = useMessage();
  6. const glob = useGlobSetting();
  7. /**
  8. * 导出文件xlsx的mime-type
  9. */
  10. export const XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  11. /**
  12. * 导出文件xlsx的文件后缀
  13. */
  14. export const XLSX_FILE_SUFFIX = '.xlsx';
  15. export function useMethods() {
  16. /**
  17. * 导出xls
  18. * @param name
  19. * @param url
  20. */
  21. async function exportXls(name, url, params, isXlsx = false) {
  22. // 生成唯一loading key,避免多操作冲突
  23. const loadingKey = `export-xls-${Date.now()}`;
  24. // 显示loading,duration:0 表示不自动关闭
  25. message.loading({ content: '正在导出文件,请稍等...', key: loadingKey, duration: 0 });
  26. try {
  27. const data = await defHttp.get({ url: url, params: params, responseType: 'blob', timeout: 1000 * 1000 }, { isTransformResponse: false });
  28. if (!data) {
  29. createMessage.warning('文件下载失败');
  30. return;
  31. }
  32. if (!name || typeof name != 'string') {
  33. name = '导出文件';
  34. }
  35. const blobOptions = { type: 'application/vnd.ms-excel' };
  36. let fileSuffix = '.xls';
  37. if (isXlsx === true) {
  38. blobOptions['type'] = XLSX_MIME_TYPE;
  39. fileSuffix = XLSX_FILE_SUFFIX;
  40. }
  41. if (typeof window.navigator.msSaveBlob !== 'undefined') {
  42. window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
  43. } else {
  44. const url = window.URL.createObjectURL(new Blob([data], blobOptions));
  45. const link = document.createElement('a');
  46. link.style.display = 'none';
  47. link.href = url;
  48. link.setAttribute('download', name + fileSuffix);
  49. document.body.appendChild(link);
  50. link.click();
  51. document.body.removeChild(link); //下载完成移除元素
  52. window.URL.revokeObjectURL(url); //释放掉blob对象
  53. }
  54. // 导出成功提示
  55. message.success({ content: '文件导出成功!', key: loadingKey, duration: 2 });
  56. } catch (error) {
  57. createMessage.error('文件导出失败!');
  58. console.error('导出失败:', error);
  59. } finally {
  60. message.destroy(loadingKey);
  61. }
  62. }
  63. /**
  64. * 导出xls post
  65. * @param name
  66. * @param url
  67. */
  68. async function exportXlsPost(name, url, params, isXlsx = false) {
  69. const loadingKey = 'export-xls-post';
  70. message.loading({ content: '正在导出,请稍等...', key: loadingKey, duration: 0 });
  71. defHttp
  72. .post({ url: url, params: params, timeout: 1000 * 1000 }, { isTransformResponse: false })
  73. .then((data) => {
  74. if (data.code == 200 && data.result) {
  75. const messageArr = data.result.split('/');
  76. const fileUrl = encodeURIComponent(messageArr[messageArr.length - 1]);
  77. if (fileUrl) {
  78. const baseApiUrl = glob.domainUrl;
  79. // 下载文件
  80. const a = document.createElement('a');
  81. // 定义下载名称
  82. a.download = name;
  83. // 隐藏标签
  84. a.style.display = 'none';
  85. // 设置文件路径
  86. a.href = `${baseApiUrl}/sys/common/static/${fileUrl}`;
  87. // 将创建的标签插入dom
  88. document.body.appendChild(a);
  89. // 点击标签,执行下载
  90. a.click();
  91. // 将标签从dom移除
  92. document.body.removeChild(a);
  93. message.success({ content: '导出成功!', key: loadingKey, duration: 2 });
  94. } else {
  95. message.error({ content: '下载失败!', key: loadingKey, duration: 2 });
  96. }
  97. } else {
  98. message.error({ content: '下载失败!', key: loadingKey, duration: 2 });
  99. }
  100. })
  101. .catch(() => {
  102. message.error({ content: '下载失败!', key: loadingKey, duration: 2 });
  103. })
  104. .finally(() => {
  105. message.destroy(loadingKey);
  106. });
  107. }
  108. async function exportXlsPost1(name, url, params, isXlsx = false) {
  109. const loadingKey = `export-xls-post1-${Date.now()}`;
  110. message.loading({ content: '正在导出文件,请稍等...', key: loadingKey, duration: 0 });
  111. try {
  112. const data = await defHttp.post({ url: url, data: params, responseType: 'blob' }, { isTransformResponse: false });
  113. if (!data) {
  114. createMessage.warning('文件下载失败');
  115. return;
  116. }
  117. if (!name || typeof name != 'string') {
  118. name = '导出文件';
  119. }
  120. const blobOptions = { type: 'application/vnd.ms-excel' };
  121. let fileSuffix = '.xls';
  122. if (isXlsx === true) {
  123. blobOptions['type'] = XLSX_MIME_TYPE;
  124. fileSuffix = XLSX_FILE_SUFFIX;
  125. }
  126. if (typeof window.navigator.msSaveBlob !== 'undefined') {
  127. window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
  128. } else {
  129. const url = window.URL.createObjectURL(new Blob([data], blobOptions));
  130. const link = document.createElement('a');
  131. link.style.display = 'none';
  132. link.href = url;
  133. link.setAttribute('download', name + fileSuffix);
  134. document.body.appendChild(link);
  135. link.click();
  136. document.body.removeChild(link); //下载完成移除元素
  137. window.URL.revokeObjectURL(url); //释放掉blob对象
  138. }
  139. message.success({ content: '文件导出成功!', key: loadingKey, duration: 2 });
  140. } catch (error) {
  141. createMessage.error('文件导出失败!');
  142. console.error('导出失败:', error);
  143. } finally {
  144. message.destroy(loadingKey);
  145. }
  146. }
  147. /**
  148. * 导入xls
  149. * @param data 导入的数据
  150. * @param url
  151. * @param success 成功后的回调
  152. */
  153. async function importXls(data, url, success) {
  154. const loadingKey = `import-xls-${Date.now()}`;
  155. message.loading({ content: '正在导入文件,请稍等...', key: loadingKey, duration: 0 });
  156. const isReturn = (fileInfo) => {
  157. try {
  158. if (fileInfo.code === 201) {
  159. const {
  160. message,
  161. result: { msg, fileUrl, fileName },
  162. } = fileInfo;
  163. const href = glob.uploadUrl + fileUrl;
  164. createWarningModal({
  165. title: message,
  166. centered: false,
  167. content: `<div>
  168. <span>${msg}</span><br/>
  169. <span>具体详情请<a href = ${href} download = ${fileName}> 点击下载 </a> </span>
  170. </div>`,
  171. });
  172. } else if (fileInfo.code === 500 || fileInfo.code === 510) {
  173. createMessage.error(fileInfo.message || `${data.file.name} 导入失败`);
  174. } else {
  175. createMessage.success(fileInfo.message || `${data.file.name} 文件上传成功`);
  176. }
  177. } catch (error) {
  178. console.log('导入的数据异常', error);
  179. createMessage.error('文件导入异常!');
  180. } finally {
  181. // 关闭loading
  182. message.destroy(loadingKey);
  183. typeof success === 'function' ? success(fileInfo) : '';
  184. }
  185. };
  186. try {
  187. await defHttp.uploadFile({ url }, { file: data.file }, { success: isReturn });
  188. } catch (error) {
  189. // 异常时强制关闭loading
  190. message.destroy(loadingKey);
  191. createMessage.error('文件导入失败!');
  192. console.error('导入失败:', error);
  193. }
  194. }
  195. return {
  196. handleExportXls: (name: string, url: string, params?: object) => exportXls(name, url, params),
  197. handleExportXlsPost: (name: string, url: string, params?: object) => exportXlsPost(name, url, params),
  198. exportXlsGetBlob: (name: string, url: string, params?: object) => exportXls(name, url, params),
  199. exportXlsPostBlob: (name: string, url: string, params?: object) => exportXlsPost1(name, url, params),
  200. handleImportXls: (data, url, success) => importXls(data, url, success),
  201. handleExportXlsx: (name: string, url: string, params?: object) => exportXls(name, url, params, true),
  202. };
  203. }