1、先说get的方法,比较简单,直接超链接跳转即可:
const action=url+`/modelTemplate/exportExcel/${Id}` //完整的接口地址
window.open(action, '_self'); // _self参数设置是为了不跳转到新界面上去
2、post方法:
const config={
responseType: 'blob' //这个一定要设置,否则会出现文件下载后打不开的情况
}
axios.post(url,params,config).then(res=>{
let blob=new Blob([res],{ //设置数据源
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; application/octet-stream' //设置文件格式
})
let objectUrl = URL.createObjectURL(blob); //创建下载的链接
let a = document.createElement("a");
a.href = objectUrl;
a.download = ‘fileName’; //设置文件名
//下面这个写法兼容火狐
a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
window.URL.revokeObjectURL(blob); //释放bolb对象
})
这里如果有对文件名的要求,一般都返回在响应头的’content-disposition’下: