想问下后端下载接口返回了文件,为啥用 js 转 blob 后打不开了...

看搜出来的 blob 那里是[res.data]这里在 request.js 文件封装取过了,应该只要拿 res 就好了吧
res.data
打不开是怎么个打不开法,把 blob 内容导出来,重命名为 .xlsx,然后试试。
为什么不是 res.data
res 就是我图二的 data 内容了,还需要 res.data 嘛,封装过了
service.interceptors.response.use(
response => {
console.log(response)
if (response.headers.password) {
return response.headers.password
} else {
return response.data
}
})
返回的是乱码不知道怎么导出,直接用 blob 下载嘛,
type 换这个试试"application/vnd.ms-excel"
下载后直接打开提示这个,https://cdn.markone.xyz/images/20200414153314.png https://cdn.markone.xyz/images/20200414153336.png
为甚么不用 location.href 跳转过去下载。。
直接打开下的是 xlsx 格式的是能打开的,对照 MIME 表这个是 xls 吧,不过试了下也不可以
因为下载文件的时候后端要求带上 token.....直接跳过去貌似没办法 header 带
对比下文件
可以看下 6 楼图,因为 blob 后文件打不开所以对比大小由几十 kb 增加到了几百 kb
你这个 PK 开头的文件是 zip 文件吧,确定是直接返回 excel 文件?
不会没写 responseType 吧?
但是我直接访问接口地址是下下来的 excel 文件
是不是后端返回的数据不是 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});
};
转一下试试?
 才设置了下好像没变化
哦 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");
https://paste.ubuntu.com/p/NPwXWtvgky/
特地找了下之前的代码
后端返回是 Content-Type=application/octet-stream
抱歉,第三个 mime 参数写错了
补充:ajax 或 axios 请求的 responseType 声明为 blob
第二个'hello'那里报错了,所以我改成了 var blob = new Blob([u8arr], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // 这里放文件类型,后台返回的 response 会有这个文件类型,放进来就行
})
生成的文件大小貌似和下载的差不多,下载 85,生成 81k 。。。但是好像仍然打不开
前段时间我经常遇到这个问题 如果前端正确设置了 responseType 和 Blob 的 type (MIME type) 还有问题 那就是后端问题