window.location.href换成用get请求下载文件
- 我们一般是用window.location.href 的方式下载文件对象,但是这样前端界面就不知道什么时候后台才把数据封装好,如果数据量过大的时候,界面就会出现按钮点击了,但是界面不动的假死现象,这样我们就需要使用获取文件流的方式让js获取数据去下载,在这期间,js就能很好的进行相应的处理反馈;
window.location.href = "api/v1/download";
axios({
method: 'get',
headers: {
'Content-Type': 'application/vnd.ms-excel',
},
url: "api/v1/download/name",
responseType: 'blob'
}).then(res => {
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
});
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
const fname = 'demo列表';
link.href = objectUrl;
link.setAttribute('download', fname);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(URL);
})