前端接口调用
this.axios.post("/api/doorStatistics/exportEarlyWarningData", params,{
timeout: 0,
responseType: "blob",
headers: {
"Content-Type": "application/json;application/octet-stream"
}
}).then(res => {
console.log(res);
let fileName = item.title+item.version;
this.$utils.binaryDownload(res,fileName);//具体下载方法在下方
})
后端返回数据
显示
打印res
]
二进制流下载方法
binaryDownload(res,cfileName) {
if (!res.data) {
this.$message.error("文件下载失败!");
return false;
}
// 这里res.data是返回的是二进制文件流
const blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8', endings: 'transparent' }); // 将二进制文件流转为blob
let contentDisposition = res.headers['content-disposition']; // 从Response Headers中获取content-disposition的值, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
let patt = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; // 设置正则表达式匹配格式
let result = patt.exec(contentDisposition); // 通过正则表达式提取“filename=” 后的值
let filename = result[1]; // 提取文件名
let list = filename.split('.');
let suffix = list[list.length-1];
// 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, decodeURI(filename));
} else {
const blobURL = window.URL.createObjectURL(blob); // 把blob转化为一个Blob URL
const aLink = document.createElement('a'); // 创建a标签,用于跳转至下载链接
aLink.href = blobURL; // 设置a标签href值
if(cfileName){
aLink.setAttribute('download', decodeURI(cfileName +'.'+ suffix)); // 设置下载文件名称
}else{
if (res.config.params.fileType == undefined || res.config.params.fileType == '' || res.config.params.fileType == null) {
aLink.setAttribute('download', res.config.params.fileName); // 设置下载文件名称
} else {
aLink.setAttribute('download', res.config.params.fileName + '.' + res.config.params.fileType); // 设置下载文件名称
}
}
// 兼容:某些浏览器不支持HTML5的download属性
if (typeof aLink.download === 'undefined') {
aLink.setAttribute('target', '_blank');
}
aLink.style.display = 'none'; // 隐藏a标签
document.body.appendChild(aLink); // a标签插入到body中
aLink.click(); // 模拟a标签点击事件 使其下载
document.body.removeChild(aLink); // 移除a标签
window.URL.revokeObjectURL(blob); //释放掉blob对象
}
},