情景:后端为post请求,且接口返回为excel文件流
方法:可以使用原生XMLHttpRequest和原生fetch两种方法
// 下载模板
doDownLoad(){
if (this.upSelectRows.length === 0) {
this.$message.warning("请选择要提交的数据!");
return;
}
this.downloadTemp2('授权支付明细文件','/df/pay/common/new/exportExcel',{pay_cert_no: this.upSelectRows[0].pay_cert_no})
},
// 方法1:使用原生XMLHttpRequest去请求,并下载文件
downloadTemp(filename,url,param){
const req = new XMLHttpRequest();
req.open('POST', url,true)
req.responseType = 'blob'
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
let _this = this
req.onload = function() {
let blob = this.response
_this.download(blob,filename)
};
req.send(qs.stringify(param))
},
// 方法2:使用原生fetch去请求,并下载文件
downloadTemp2(filename,url,param){
fetch(url,{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: qs.stringify(param)
}).then(res => res.blob())
.then(blob => {
this.download(blob,filename)
})
},
download(blob,filename){
let bolbUrl = window.URL.createObjectURL(blob)
let a = document.createElement("a");
document.body.appendChild(a);
a.href = bolbUrl;
a.download = filename;
a.click();
document.body.removeChild(a);
},
备注:两种方法的选择:
1、若项目基于XMLHttpRequest,则最好选择XMLHttpRequest
2、若项目基于fetch,则最好选择fetch