直接上代码
// responseType: 'blob' 很重要,这里举例为post请求
axios.post(url,params,{responseType: 'blob'})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// 前端接收并下载
download(param).then(res => {
console.log(res, "返回数据");
// 创建blob对象,type注意与后端返回的文件类型保持一致,这里是doc,docx 类型的
// type也可以不填
var blob = new Blob([res.data], { type: 'application/msword;charset=utf-8' });
let url = window.URL.createObjectURL(blob);//生成一个Blob URL
console.log(url)
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download','下载文件.doc');// 给下载框的下载文件名赋值
document.body.appendChild(link);
link.click() //模拟在按钮上的一次鼠标单击
URL.revokeObjectURL(link.href); // 释放URL 对象
})