需求:后台根据前端传递的参数动态生成xlsx文件模板,提供给前端下载。前端点击按钮下载文件。
下载函数:
function downloadFile(){
const downLoadhref = `api/xxxxxxxxxxxxxxxx`
const a = document.createElement("a");
a.download = '文件模板';
a.style.display = "none";
a.href = downLoadhref;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
问题:单纯的下载函数如果遇到正确生成的xlsx文件是能正常下载的,但是如果后台生成模板错误或者有报错信息的话直接下载带报错信息的.json文件。
解决:通过ajax下载,拿到response header头部信息,判断返回类型,如果是‘application/x-msexecl’则调取下载函数,否则提示错误,避免下载.json文件。
$.ajax({
type:'get',
url:'api/xxxxxxxxxxx', //请求api
data:{}, //传递参数
success: function(res,status,xhr){
const xhrMessage = xhr.getResponseHeader("Content-Type").split(';')[0]
if(xhrMessage==='application/x-msexecl'){
// 调用downloadFile()方法
}else{
const {errCode,msg} = res //根据后台返回数据酌情修改
if(errCode){
console.error(msg)
}
}
},
error: function(res){
console.log(res)
}
})
注意点:$.ajax的scuccess带三个参数(返回值,请求状态,xhr对象),通过xhr.getResponseHeader(“Content-Type”) 获取信息做条件判断