请求前设置:
config.responseType = “blob”
config.headers: {
“Content-Type”: “application/json”
}
数据返回后:
//处理异常 显示后台抛错信息
//‘与后台约定数据出错返回格式’
if(res.type == ‘application/json’){
// 创建读取文件的FileReader 对象
var reader = new FileReader()
//开始读取指定的Blob中的内容。一旦完成,result属性中将包含一个字符串以表示所读取的文件内容。
reader.readAsText(res)
// 处理load事件。该事件在读取操作完成时触发
reader.onload = e => {
if(JSON.parse(e.target.result).code != 1001){
//显示出错信息
}
}
return false
}
//取值下载excel
const blob = new Blob([res]); //创建blob对象
const fileName = “订单列表.xls”; //自定义表名xlsx
const elink = document.createElement(“a”); //创建标签
elink.download = fileName; // a标签dowmload属性赋值
elink.style.display = “none”; // 隐藏a标签
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click(); // 点击事件
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink); // 移除a标签