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 ,我是沒看(攤手)