需求
后台需要根据选定的 厂商和设备型号,生成对应的excel表格模版
通过接口返回文件流,采用blob接收
image.png
问题
直接将blob文件流存储为指定文件名,前端还要自己起个名字
后在接口response的header中发现了如下参数content-disposition,那么优雅的保存blob的文件就有了方法
image.png
代码
//axios的请求方式
axios({
url: url+"?a=1&b=2",
method: "get",
responseType:'blob'
})
.then( res => {
let fileName = (res.headers['content-disposition'].split("="))[1]
let blob = res.data
if (typeof window.navigator.msSaveBlob !== 'undefined') {
/*
* For IE
* >=IE10
*/
window.navigator.msSaveBlob(blob, fileName);
} else {
/*
* For Non-IE (chrome, firefox)
*/
var URL = window.URL || window.webkitURL;
var objectUrl = URL.createObjectURL(blob);
if (fileName) {
var a = document.createElement('a');
if (typeof a.download === 'undefined') {
window.location = objectUrl;
} else {
a.href = objectUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
}
} else {
window.location = objectUrl;
}
}
})
.finally(r => {
});