0
点赞
收藏
分享

微信扫一扫

axios 下载文件流

书呆鱼 2021-09-24 阅读 149
方法封装
/**
* 二进制流下载
* @param {Object} res
*/

binaryDownload(res){
if(!res.data){
this.$message.error("文件下载失败!");
return false;
}

// 这里res.data是返回的是二进制文件流
const blob = new Blob([res.data], {type: 'application/octet-stream', endings: 'transparent'}); // 将二进制文件流转为blob

let contentDisposition = res.headers['content-disposition']; // 从Response Headers中获取content-disposition的值, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
let patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*'); // 设置正则表达式匹配格式
// let patt = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; // 设置正则表达式匹配格式
let result = patt.exec(contentDisposition); // 通过正则表达式提取“filename=” 后的值
let filename = result[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值
aLink.setAttribute('download', filename); // 设置下载文件名称
// 兼容:某些浏览器不支持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对象
}
}
调用下载接口
downLoadDocument(row) {
this.$axios.product.productRepositoryFileDown({
params:{
fileName: row.name,
fileType: row.fileType,
id: row.id,
productId: this.storage.productId,
versionId: this.versionId,
userId: this.storage.userId
},
timeout: 0,
responseType: "blob",
headers: {
"Content-Type": "application/json;application/octet-stream"
}
}).then(res => {
// 此处为下载
this.$utils.binaryDownload(res);
})
}
举报

相关推荐

0 条评论