理解前端blob和ArrayBuffer,前端接受文件损坏的问题
1 downloadTemplate().then(res =>{ 2 3 const data = res.data 4 const url = window.URL.createObjectURL(new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})) 5 const link = document.createElement('a') 6 link.style.display = 'none' 7 link.href = url 8 link.setAttribute('download', 'Template.xlsx') 9 document.body.appendChild(link) 10 link.click() 11 document.body.removeChild(link) 12 13 });
上面是常规的接受接口blob流下载文件的代码 ,实际过程中出现 后端包不同 接收文件出现损坏的情况
解决 1. 添加
responseType
1 export function downloadTemplate() { 2 return request({ 3 url: '/downloadTemplate' , 4 method: 'get', 5 responseType:"blob" 6 }) 7 }
2. 解决不了的话 如果你的下载文件属于模板类不变的文件 ,直接放在public下与index.html同级 这样你就可以
const link = document.createElement('a') link.style.display = 'none' link.href = “./xxxxx” link.setAttribute('download', 'Template.xlsx') document.body.appendChild(link) link.click() document.body.removeChild(link)
过程中发现一个有趣的东西Blob 和ArrayBuffer
Blob对象
Blob也是比较有意思,mdn上的解释是Blob对象表示不可变的类似文件对象的原始数据。Blob表示不一定是JavaScript原生形式的数据。
_其实就是英文Binary large Object,mysql有此类型数据结构
let blog = new Blob(arrya, options);
Blob() 构造函数返回一个新的 Blob 对象。
array 是一个由ArrayBuffer, ArrayBufferView, Blob, DOMString 等对象构成的 Array ,或者其他类似对象的混合体,它将会被放进 Blob。
options 是一个可选的BlobPropertyBag字典,它可能会指定如下两个属性:
**type**,默认值为 "",它代表了将会被放入到blob中的数组内容的**MIME**类型。
ArrayBuffer涉及面比较广,我的理解是ArrayBuffer代表内存之中的一段二进制数据,一旦生成不能再改。可以通过视图(TypedArray和DataView)进行操作。
TypedArray数组只是一层视图,本身不储存数据,它的数据都储存在底层的ArrayBuffer对象之中, 所以通过同一个arraybuffer生成的TypedArray共享内存数据。
看这些基本就差不多了 还想看多的https://zyc88.blog.csdn.net/article/details/101271056 ,我是没看(摊手)