get请求,导出文件
/** * @author * @function: 导出文件(get请求) * @param {*} linkUrl 下载链接 */ let exportFileByGet = function (linkUrl) { if (!linkUrl) { return false; } if ( navigator.userAgent.indexOf("Chrome") > -1 && navigator.userAgent.indexOf("Safari") > -1 ) { var a = document.createElement("a"); a.href = linkUrl; a.click(); } else { window.open(linkUrl, "_blank"); } };
post请求,导出文件
/** * @author: * @function: 导出文件(post请求) * @param {*} queryUrl 请求链接 * @param {*} queryParams 请求参数 * @param {*} cb 回调函数 * */ let exportFileByPost = function ( queryUrl, queryParams = {}, cb ) { if (!queryUrl) { return false; } this.$axios() .post(queryUrl, queryParams, { responseType: "blob", }) .then( (res) => { // 异常处理 if (res.data.type == "application/json") { let reader = new FileReader(); reader.readAsText(res.data, "utf-8"); reader.onload = function (e) { let result = JSON.parse(reader.result); this.$message.error(result.msg || "error!"); cb(); }; return false; } let fileName = ""; if (res.headers["content-disposition"]) { fileName = decodeURI( res.headers["content-disposition"].split(`filename=`)[1] //此处根据实际返回下载文件名称分割 ); } let type = res.headers["content-type"]; if (!type) { this.$message.error("file type error!"); cb(); } let blob = new Blob([res.data], { type: type, //根据返回文件类型 }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, fileName); } else { // 非IE下载 const elink = document.createElement("a"); elink.style.display = "none"; elink.href = URL.createObjectURL(blob); if (fileName) elink.download = fileName; document.body.appendChild(elink); elink.click(); setTimeout(() => { URL.revokeObjectURL(elink.href); // 释放URL对象 document.body.removeChild(elink); }, 5000); //解决部分浏览器下载时“无此文件”问题 } cb(); }, (res) => { this.$message.error(res.msg || "error!"); cb(); } ); };