直接下载:适用于简单场景,不发送请求直接使用浏览器获取文件
/*** @description: 下载图片/文件* @return {*}*/
export const download = (url = '', newUrl) => {const iframe = document.createElement('a');if (newUrl) {iframe.href = newUrl;} else {iframe.href = (window.DCIMAPP.downloadPrefix || '') + url;}iframe.download = document.cookie ? document.cookie.split('; ') : [];document.querySelector('body').appendChild(iframe);iframe.click();document.querySelector('body').removeChild(iframe);
};
发送请求get/post:适合复杂的下载场景
export const filterexport = ({url = '', params, fun,method="post"}) => {function getFileName(fileName, response) {// 需要响应设置此header暴露给外部,才能获取到let contentDisposition = response.headers['content-disposition'];if (contentDisposition) {// 正则获取filename的值let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;let matches = filenameRegex.exec(contentDisposition);if (matches != null && matches[1]) {fileName = matches[1].replace(/['"]/g, '');}// 通过 URLEncoder.encodeURIComponent(pFileName, StandardCharsets.UTF_8.name()) 加密编码的, 使用decodeURIComponent(fileName) 解密// fileName = decodeURIComponent(fileName)// 通过 new String(pFileName.getBytes(), StandardCharsets.ISO_8859_1) 加密编码的, 使用decodeURIComponent(escape(fileName)) 解密var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串if (userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') == -1) {return fileName;}fileName = decodeURIComponent(escape(fileName));}return fileName;}let useUrl = '';// iframe.href = (window.DCIMAPP.downloadPrefix || '') + url;useUrl = (window.DCIMAPP.downloadPrefix || '') + url;if (useUrl[0] == '/') useUrl = useUrl.substr(1);axios({url: window.DCIMAPP.bpmDomain + useUrl,method: method,formateResponse: () => {return false;},handleResponse: (res, code, response) => {return response;},responseType: 'blob',data: params,}).then((res) => {if (res.data.type.split('/')[1] == 'json') {const reader = new FileReader();reader.readAsText(res.data, 'utf-8');reader.onload = () => {res = JSON.parse(reader.result);if (res.code && res.code !== 100000) {prompt.warn(res.msg);}};return;} else if (fun && res.data) {fun();prompt.success(intl.get('7d372ced-178d-485c-a1b1-3538c51700db').d('导出成功'));}const iframe = document.createElement('a');let url = window.URL.createObjectURL(new Blob([res.data]));let fileName = '';fileName = getFileName(fileName, res);iframe.download = fileName;iframe.href = url;document.querySelector('body').appendChild(iframe);iframe.click();document.querySelector('body').removeChild(iframe);});
};