使用axios获取并下载文件
/** * 导出文件方法 * @param {String} method [请求方式] * @param {String} url [请求的url地址] * @param {Object} params [请求时携带的参数] * @param {String} fileName [导出的文件名,例:test.xlsx] */ function DOWNLOAD(method="post",url, params, fileName) { return new Promise((resolve, reject) => { axios({ method: method, url: url, params: params, responseType: 'blob' }) .then(res => { let reader = new FileReader(); let data = res.data; reader.onload = e => { if (e.target.result.indexOf('Result') != -1 && JSON.parse(e.target.result).Result == false) { // 进行错误处理 } else { if (!fileName) { let contentDisposition = res.headers['content-disposition']; if (contentDisposition) { fileName = window.decodeURI(res.headers['content-disposition'].split('=')[2].split("''")[1], "UTF-8"); } } executeDownload(data, fileName); } }; reader.readAsText(data); resolve(res.data); }) }); } // 模拟点击a 标签进行下载 function executeDownload(data, fileName) { if (!data) { return } let url = window.URL.createObjectURL(new Blob([data])); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); document.body.removeChild(link); }