前端处理Blob,并且封装blob的axios请求
最近做的项目有下载功能;后端返回的数据是文件流。封装一个blob专用的axios请求。其他就正常请求就可以啦!那么前端要怎么处理呢?欢迎各位大佬指教~~
·
最近做的项目有下载功能;后端返回的数据是文件流
如图:
那么前端要怎么处理呢?
封装一个blob专用的axios请求
const serviceBlob = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
responseType: 'blob', //必须设置 响应类型为blob
})
serviceBlob.interceptors.response.use(
response => {
// 声明blob变量
let blob = new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
});
let downloadElement = document.createElement("a");
// 下载地址
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
// 处理formData数据
let fileName = "";
// FormData类型
if (response.config.data instanceof FormData) {
var object = {};
response.config.data.forEach((value,key) => object[key] = value);
fileName = object.name + '-模板';
} else {
fileName = JSON.parse(response.config.data)[0];
}
downloadElement.download = fileName + '.xlsx';//自定义的文件名
document.body.appendChild(downloadElement);
downloadElement.click();
//下载完一定要移除
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
fileName = "";
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default serviceBlob;
其他就正常请求就可以啦!
欢迎各位大佬指教~~
更多推荐
已为社区贡献1条内容
所有评论(0)