

axios({ method: 'get', url: 'http://192.168.1.104:9100/smartmarket/open/downloadTaskMsgTemplate', responseType: 'blob' }).then(res => { console.log(res) const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) if ('download' in document.createElement('a')) { // 非IE下载 const elink = document.createElement('a') // elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) // 释放URL 对象 document.body.removeChild(elink) } else { // IE10+下载 // navigator.msSaveBlob(blob, fileName) } }) 已经解决,感谢各位,除了转blob以外要设置responseType: 'blob' mock会改掉这个,所以参考https://github.com/PanJiaChen/vue-element-admin/issues/1466
1 xiaohantx OP 看搜出来的 blob 那里是[res.data]这里在 request.js 文件封装取过了,应该只要拿 res 就好了吧 |
2 yaphets666 2020-04-14 15:27:51 +08:00 res.data |
3 yidinghe 2020-04-14 15:28:16 +08:00 打不开是怎么个打不开法,把 blob 内容导出来,重命名为 .xlsx,然后试试。 |
4 U7Q5tLAex2FI0o0g 2020-04-14 15:28:54 +08:00 为什么不是 res.data |
5 xiaohantx OP @yaphets666 @littleylv res 就是我图二的 data 内容了,还需要 res.data 嘛,封装过了 service.interceptors.response.use( respOnse=> { console.log(response) if (response.headers.password) { return response.headers.password } else { return response.data } }) |
6 xiaohantx OP @yidinghe 返回的是乱码不知道怎么导出,直接用 blob 下载嘛, |
7 yaphets666 2020-04-14 15:33:23 +08:00 type 换这个试试"application/vnd.ms-excel" |
8 xiaohantx OP |
9 rming 2020-04-14 15:35:42 +08:00 为甚么不用 location.href 跳转过去下载。。 |
10 xiaohantx OP @yaphets666 直接打开下的是 xlsx 格式的是能打开的,对照 MIME 表这个是 xls 吧,不过试了下也不可以 |
14 zjsxwc 2020-04-14 15:44:52 +08:00 你这个 PK 开头的文件是 zip 文件吧,确定是直接返回 excel 文件? |
15 yaphets666 2020-04-14 15:44:58 +08:00 不会没写 responseType 吧? |
17 U7Q5tLAex2FI0o0g 2020-04-14 15:46:30 +08:00 是不是后端返回的数据不是 blob 而是 dataurl ? var dataURLtoBlob = function(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type:mime}); }; 转一下试试? |
18 xiaohantx OP @yaphets666  才设置了下好像没变化 |
19 zjsxwc 2020-04-14 15:54:02 +08:00 @xiaohantx 哦 OOXML 就是 zip 的 excel 试试 转 u8 数组 var n, bstr, u8arr; bstr = res; n = bstr.length; u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } var blob = new Blob([u8arr], "hello.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); |
20 Latin 2020-04-14 15:54:44 +08:00 |
22 Latin 2020-04-14 15:58:52 +08:00 补充:ajax 或 axios 请求的 responseType 声明为 blob |
23 xiaohantx OP @zjsxwc 第二个'hello'那里报错了,所以我改成了 var blob = new Blob([u8arr], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // 这里放文件类型,后台返回的 response 会有这个文件类型,放进来就行 }) 生成的文件大小貌似和下载的差不多,下载 85,生成 81k 。。。但是好像仍然打不开 |