首先Ajax无法下载文件
浏览器的GET(frame,a)和POST(from)请求具有如下特点
- response会交由浏览器处理
- response内容可以为二进制文件,字符串等
ajax请求特点
- response会交由Javascrip处理
- response内容仅为字符串
因此,ajax本身无法触发浏览器的下载功能
在我和后台的交互中使用Web API中的Blob
详解:https://juejin.im/post/59e35d0e6fb9a045030f1f35
创建 Blob对象将后台返回的数据流填充对象中.利用a标签跳转打开新的连接下载对象文件
exportExcel(url,title,params){
axios.$post(`${this.item.url}/export`,this.tableJson,{
responseType: 'blob', // 表明返回服务器返回的数据类型
}).then(res=>{
const blob =new Blob([res.data]);
const fileName = `${title}.xlsx`
const elink =document.createElement('a');
elink.download=fileName
elink.style.display='none'
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
})
},