1、先将请求头的responseType
设置为blob
const service = axios.create({
baseURL: process.env.VUE_APP_API_BASE_URL,
// withCredentials: true, // send cookies when cross-domain requests
timeout: 50000 // request timeout
});
// request interceptor
service.interceptors.request.use(
config => {
if (['/m/person/info/export', '/m/person/info/download'].indexOf(config.url) > -1) {
config.responseType = 'blob';
}
return config;
},
error => {
console.log(error); // for debug
return Promise.reject(error);
}
);
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data;
// 如果是返回的excel文件流
if (response.headers['content-type'] === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8') {
return res;
} else {
return res;
}
},
(error) => {
console.log('错误信息:' + error); // for debug
__vue.$message.error('系统异常');
return null;
}
);
2、文件流处理
personExport().then(res => {
if (res) {
let blob = new Blob([res], { type: 'application/x-xls' });
const a = document.createElement('a');
// 创建URL
const blobUrl = window.URL.createObjectURL(blob);
a.download = '员工信息.xlsx';
a.href = blobUrl;
document.body.appendChild(a);
// 下载文件
a.click();
// 释放内存
URL.revokeObjectURL(blobUrl);
document.body.removeChild(a);
}
});
网友评论