useMethods.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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: 5 * 60 * 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. if (error && error['code'] == 'ECONNABORTED') {
  58. if (url.includes('/export/historydata') || url.includes('/ventanalyAlarmLog/exportXls')) {
  59. createMessage.error('导出的数据量太大,请选择合理的时间范围和间隔时间分批导出!');
  60. } else {
  61. createMessage.error('导出的数据量太大,导出失败!');
  62. }
  63. } else {
  64. createMessage.error('文件导出失败!');
  65. }
  66. } finally {
  67. message.destroy(loadingKey);
  68. }
  69. }
  70. /**
  71. * 导出xls post
  72. * @param name
  73. * @param url
  74. */
  75. async function exportXlsPost(name, url, params, isXlsx = false) {
  76. const loadingKey = 'export-xls-post';
  77. message.loading({ content: '正在导出,请稍等...', key: loadingKey, duration: 0 });
  78. defHttp
  79. .post({ url: url, params: params, timeout: 5 * 60 * 1000 }, { isTransformResponse: false })
  80. .then((data) => {
  81. if (data.code == 200 && data.result) {
  82. const messageArr = data.result.split('/');
  83. const fileUrl = encodeURIComponent(messageArr[messageArr.length - 1]);
  84. if (fileUrl) {
  85. const baseApiUrl = glob.domainUrl;
  86. // 下载文件
  87. const a = document.createElement('a');
  88. // 定义下载名称
  89. a.download = name;
  90. // 隐藏标签
  91. a.style.display = 'none';
  92. // 设置文件路径
  93. a.href = `${baseApiUrl}/sys/common/static/${fileUrl}`;
  94. // 将创建的标签插入dom
  95. document.body.appendChild(a);
  96. // 点击标签,执行下载
  97. a.click();
  98. // 将标签从dom移除
  99. document.body.removeChild(a);
  100. message.success({ content: '导出成功!', key: loadingKey, duration: 2 });
  101. } else {
  102. message.error({ content: '下载失败!', key: loadingKey, duration: 2 });
  103. }
  104. } else {
  105. message.error({ content: '下载失败!', key: loadingKey, duration: 2 });
  106. }
  107. })
  108. .catch((error) => {
  109. if (error && error['code'] == 'ECONNABORTED') {
  110. if (url.includes('/export/historydata') || url.includes('/ventanalyAlarmLog/exportXls')) {
  111. createMessage.error('导出的数据量太大,请选择合理的时间范围和间隔时间分批导出!');
  112. } else {
  113. createMessage.error('导出的数据量太大,导出失败!');
  114. }
  115. } else {
  116. message.error({ content: '下载失败!', key: loadingKey, duration: 2 });
  117. }
  118. })
  119. .finally(() => {
  120. message.destroy(loadingKey);
  121. });
  122. }
  123. async function exportXlsPost1(name, url, params, isXlsx = false) {
  124. const loadingKey = `export-xls-post1-${Date.now()}`;
  125. message.loading({ content: '正在导出文件,请稍等...', key: loadingKey, duration: 0 });
  126. try {
  127. const data = await defHttp.post({ url: url, data: params, responseType: 'blob' }, { isTransformResponse: false });
  128. if (!data) {
  129. createMessage.warning('文件下载失败');
  130. return;
  131. }
  132. if (!name || typeof name != 'string') {
  133. name = '导出文件';
  134. }
  135. const blobOptions = { type: 'application/vnd.ms-excel' };
  136. let fileSuffix = '.xls';
  137. if (isXlsx === true) {
  138. blobOptions['type'] = XLSX_MIME_TYPE;
  139. fileSuffix = XLSX_FILE_SUFFIX;
  140. }
  141. if (typeof window.navigator.msSaveBlob !== 'undefined') {
  142. window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
  143. } else {
  144. const url = window.URL.createObjectURL(new Blob([data], blobOptions));
  145. const link = document.createElement('a');
  146. link.style.display = 'none';
  147. link.href = url;
  148. link.setAttribute('download', name + fileSuffix);
  149. document.body.appendChild(link);
  150. link.click();
  151. document.body.removeChild(link); //下载完成移除元素
  152. window.URL.revokeObjectURL(url); //释放掉blob对象
  153. }
  154. message.success({ content: '文件导出成功!', key: loadingKey, duration: 2 });
  155. } catch (error) {
  156. if (error && error['code'] == 'ECONNABORTED') {
  157. if (url.includes('/export/historydata') || url.includes('/ventanalyAlarmLog/exportXls')) {
  158. createMessage.error('导出的数据量太大,请选择合理的时间范围和间隔时间分批导出!');
  159. } else {
  160. createMessage.error('导出的数据量太大,导出失败!');
  161. }
  162. } else {
  163. message.error({ content: '下载失败!', key: loadingKey, duration: 2 });
  164. }
  165. } finally {
  166. message.destroy(loadingKey);
  167. }
  168. }
  169. /**
  170. * 导入xls
  171. * @param data 导入的数据
  172. * @param url
  173. * @param success 成功后的回调
  174. */
  175. async function importXls(data, url, success) {
  176. const loadingKey = `import-xls-${Date.now()}`;
  177. message.loading({ content: '正在导入文件,请稍等...', key: loadingKey, duration: 0 });
  178. const isReturn = (fileInfo) => {
  179. try {
  180. if (fileInfo.code === 201) {
  181. const {
  182. message,
  183. result: { msg, fileUrl, fileName },
  184. } = fileInfo;
  185. const href = glob.uploadUrl + fileUrl;
  186. createWarningModal({
  187. title: message,
  188. centered: false,
  189. content: `<div>
  190. <span>${msg}</span><br/>
  191. <span>具体详情请<a href = ${href} download = ${fileName}> 点击下载 </a> </span>
  192. </div>`,
  193. });
  194. } else if (fileInfo.code === 500 || fileInfo.code === 510) {
  195. createMessage.error(fileInfo.message || `${data.file.name} 导入失败`);
  196. } else {
  197. createMessage.success(fileInfo.message || `${data.file.name} 文件上传成功`);
  198. }
  199. } catch (error) {
  200. console.log('导入的数据异常', error);
  201. createMessage.error('文件导入异常!');
  202. } finally {
  203. // 关闭loading
  204. message.destroy(loadingKey);
  205. typeof success === 'function' ? success(fileInfo) : '';
  206. }
  207. };
  208. try {
  209. await defHttp.uploadFile({ url }, { file: data.file }, { success: isReturn });
  210. } catch (error) {
  211. // 异常时强制关闭loading
  212. message.destroy(loadingKey);
  213. createMessage.error('文件导入失败!');
  214. console.error('导入失败:', error);
  215. }
  216. }
  217. return {
  218. handleExportXls: (name: string, url: string, params?: object) => exportXls(name, url, params),
  219. handleExportXlsPost: (name: string, url: string, params?: object) => exportXlsPost(name, url, params),
  220. exportXlsGetBlob: (name: string, url: string, params?: object) => exportXls(name, url, params),
  221. exportXlsPostBlob: (name: string, url: string, params?: object) => exportXlsPost1(name, url, params),
  222. handleImportXls: (data, url, success) => importXls(data, url, success),
  223. handleExportXlsx: (name: string, url: string, params?: object) => exportXls(name, url, params, true),
  224. };
  225. }