1、创建blob响应类型的axios对象
const blobAxios = axios.create({
responseType: 'blob',
timeout: 5 * 60 * 1000,
paramsSerializer(p) {
return Qs.stringify(p, { indices: false });
}
});
//用于增加token鉴权,对于开放文件无需设置
blobAxios.interceptors.request.use((config) => {
const token = authToken.token;
if (token) {
config.headers.Authorization = token;
}
return config;
});
2、使用blobAxios请求文件信息
async function exportBusinessReport(url) {
const response = await blobAxios.get(url);
return downloadResponse(response);
}
3、生成a标签实现真正的下载
function downloadFile(url, filename) {
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
//获得文件名
function retriveFileName(response, defaultName = 'file') {
const disposition = response.headers['content-disposition'];
const matchGroup = /filename="?([^"^;]+)"?/.exec(decodeURIComponent(disposition));
if (_.isArray(matchGroup)) {
return matchGroup[1];
}
return defaultName;
}
function downloadResponse(response, exportFileName) {
const url = window.URL.createObjectURL(new Blob([response.data]));
const filename = exportFileName || retriveFileName(response);
const notAllowedFileType = 'application/json';
if (response.data.type !== notAllowedFileType) {
downloadFile(url, filename);
} else {
throw new StandardError({ message: '加载异常,请联系开发查看原因' });
}
}