Vue中导出Excel后台返回二进制文件流,responseType设置为‘arraybuffer‘,如果后台返回错误信息应该怎么处理?
vue中导出Excel,调用后台接口返回二进制文件流,responseType设置为'arraybuffer',如果导出数量太多出错,后台返回错误信息应该怎么处理?
·
1、正常导出的情况:(使用axios发送请求)后端返回二进制文件流
api:
//返回一个Promise(发送post请求)
export function fetchExcel(url, params) {
axios.defaults.headers.accesstoken = sessionStorage.getItem("access_token")
? AES.decrypt(sessionStorage.getItem("access_token"))
: "";
url = (process.env.NODE_ENV === "development" ? "/api" : "") + url;
return new Promise((resolve, reject) => {
axios
.post(url, params, {
responseType: "arraybuffer",
})
.then((response) => {
if (response.data.code === 401 || response.data.code === 402) {
console.log("404");
} else {
resolve(response);
}
})
.catch((error) => {
reject(error);
});
});
}
// 调用接口返回二进制文件流,使用bold转为excel:
// 导出
const exportVehicleList = () => {
data.expoerLoadingFlag = true;
Api.matchCarListExport(data.vehicleForm).then((res) => {
if (res.data) {
data.expoerLoadingFlag = false;
ElMessage.success({
message: "导出成功!",
type: "success",
});
let blob = new Blob([res.data], {
type: "application/vnd.ms-excel",
}); //type这里表示xlsx类型
let fileName = "配车信息" + Date.parse(new Date()) + ".xls";
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
document.body?.removeChild(link); //下载完成移除元素
window.URL.revokeObjectURL(link.href); //释放掉blob对象
}
} else {
data.expoerLoadingFlag = false;
ElMessage.error(res.data.errorMsg);
}
}).finally(()=>{
data.expoerLoadingFlag = false;
})
};
2、需求:后台导出量过大抛出提示
由于请求的时候设置了responseType:'arraybuffer'返回的是数据流,要取得json信息需要进行换:
let enc = new TextDecoder('utf-8')
let data = JSON.parse(enc.decode(new Uint8Array(res.data)))
将调用的Api改成:
// 导出
const exportVehicleList = () => {
data.expoerLoadingFlag = true;
Api.matchCarListExport(data.vehicleForm).then((res) => {
try {
let enc = new TextDecoder('utf-8')
let data = JSON.parse(enc.decode(new Uint8Array(res.data)));
ElMessage.error(data.errorMsg);
data.expoerLoadingFlag = false;
} catch (error) {
if(res.data) {
data.expoerLoadingFlag = false;
ElMessage.success({
message: "导出成功!",
type: "success",
});
let blob = new Blob([res.data], {
type: "application/vnd.ms-excel",
}); //type这里表示xlsx类型
let fileName = "配车信息" + Date.parse(new Date()) + ".xls";
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
document.body?.removeChild(link); //下载完成移除元素
window.URL.revokeObjectURL(link.href); //释放掉blob对象
}
} else {
data.expoerLoadingFlag = false;
ElMessage.error(res.data.errorMsg);
}
}
}).finally(()=>{
data.expoerLoadingFlag = false;
})
};
更多推荐
已为社区贡献3条内容
所有评论(0)