遇到一个需求是,选择区域的站点之后,用get请求,站点ID的数组参数可能会超过浏览器参数长度限制,最后无法下载。于是换成了post方式下载文件。
第一步:与后台沟通好response header的设置,并规定好fileName的编码方式,方便前端拿到后解析
content-disposition: attachment;fileName=%E9%81%A5%E6%84%9F%E8%A7%A3%E8%AF%91%E6%95%B0%E6%8D%AE.xls
content-type: application/octet-stream
第二步:设置axios的responseType为blob,对捕获的错误信息由blob格式转回json格式再返回
axios({
method: 'post',
url: 'xxx/xxx',
data: { ids: [1,2,3]},
responseType: 'blob'
}).then(response => {
this.exportFile(response)
}).catch((error) => {
if(error.request.responseType === 'blob') {
let errInfo = {};
let reader = new FileReader();
reader.readAsText(err.response.data, 'UTF-8');
reader.onload = function () {
errInfo = JSON.parse(reader.result);
data.error && data.error.call(this, errInfo)
};
}
else {
data.error && data.error.call(this, err.response.data)
}
})
第三步:拿到文件流后实现下载
exportFile(result){
const contentDisposition = result.headers['content-disposition'];
const filename = decodeURI(contentDisposition.split('fileName=')[1] || contentDisposition.split('filename=')[1]);
const blob = new Blob([result.data]);
const url = window.URL.createObjectURL(blob);
if (window.navigator.msSaveBlob) {
try {
window.navigator.msSaveBlob(blob, filename);
}
catch (e) {
console.log(e);
}
}
else {
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
}
}
转载自:https://blog.csdn.net/qq_39364032/article/details/103010663