因为携带的参数太多,经过评估后接口采用post请求的方式下载,记录一下实现方式,希望可以帮助到需要的人...
APICaller是项目中封装的接口请求方法 大家用自己项目的就可以,核心是配置responseType: 'blob', 然后在callback中处理res。
因为我们的rd说他们无法返回code,所以它需要跳APICaller中对code非0,走接口失败的拦截。skipCodeCheckFunc是用来跳过拦截用的callback
APICaller({
APIList0: APIList.exportCustomerExcel,
data,
header: {
responseType: 'blob',
},
skipCodeCheckFunc: (res: any) => {
// 通过res.type判断是不是接口失败了, 失败信息rd是按照application/json格式返回的
if (res.type === 'application/json') {
const reader = new FileReader(); //创建一个FileReader实例
reader.readAsText(res, 'utf-8'); //读取文件,结果用字符串形式表示
reader.onload = function () {
const { errmsg } = JSON.parse(reader.result as string);
message.error(`${errmsg}`);
};
return;
}
download(res, searchData);
},
});
type需要配,不然会报excel文件损坏 打不开
const download = (res: any, searchData: any) => {
var blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' });
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
a.href = objectUrl;
a.download = `${searchData.userId}_${new Date().getTime()}.xlsx`;
a.click();
document.body.removeChild(a);
};
接口返回失败
接口返回成功