我们大多借助a标签直接下载文件,这样做有一个缺点,如果下载文件报错,无法友好的弹出错误提示
这里提供一个方法,先ajax请求,判断返回是json还是文件流,json弹出错误提示。文件流,进行本地保存,再创建a标签进行下载
这里我用的是基于superagent的前后端请求,其他也类似,只要返回二进制流即可
/** 导出 */
private export = async () => {
const param = {xxx:xxx};
// responseType('blob') 重点
const res = await service.send({
target: this,
sar: superagent.get(service.domain + '/applyPool/excel/exportList').query({ ...param }).responseType('blob'),
resFs: [],
});
this.DownloadFile(res.res);
return true;
}
private DownloadFile = (res) => {
const filename = moment(new Date()).format('YYYY-MM-DD') + '-xxxx.xls';
if (res.body.type !== 'application/json') {
const blob = res.body;
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
let URL = window.URL;
const downloadUrl = URL.createObjectURL(blob);
if (filename) {
const a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
// document.body.appendChild(a);
a.click();
// document.body.removeChild(a);
}
} else {
window.location.href = downloadUrl;
}
}
} else {
this.blobToJson(res.body);
}
}
// 将blob数据转变为json
private blobToJson = (data) => {
const reader = new FileReader();
reader.readAsText(data, 'utf-8');
reader.onload = function (e: any) {
const result = JSON.parse(reader.result+'');
if (result.status.description || result.status.message) {
message.error(result.status.description || result.status.message);
} else {
message.error('系统错误');
}
};
}