原理就是通过a标签的href属性将二进制表格数据转化为表格,再通过download属性将文件下载到本地;
需要注意的是接口请求的数据类型要设置为 blob 类型 具体参考 axios https://www.npmjs.com/package/axios
具体的代码
1 2 3 4 5 6 7 8
| let url = window.URL.createObjectURL(res.data); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', filename); document.documentElement.appendChild(link); link.click(); document.documentElement.removeChild(link);
|
完整的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import axios from 'axios';
downloadExl(filename) { axios({ method: 'get', url: '/api/export', params: Object, responseType: 'blob' }).then(res => { let url = window.URL.createObjectURL(res.data); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', filename); document.documentElement.appendChild(link); link.click(); document.documentElement.removeChild(link); }).catch(e => { console.log('导出失败') }).finally(() => { console.log('不管导出成功/失败') }); },
|