利用后端傳來的base64數(shù)據(jù)轉(zhuǎn)化成可視的work文件
項目要求是能下載一個work表格供填寫早芭,不過在嘗試將后端數(shù)據(jù) msSaveBlob 多次失敗后,看了一下網(wǎng)上同類型的需求吟孙,提供了一個直接返回base64 捅暴,由前端 blob 格式化的思路并最終實現(xiàn)了。
總體流程是將文件數(shù)據(jù)由后端轉(zhuǎn)化成 base64蛤铜,然后初始化內(nèi)容,將每個元素均轉(zhuǎn)換為 Uint8類型丛肢,再返回指定位置的字符的 Unicode 編碼围肥,接著將編碼 Blob 化,指定其類型為 docx 蜂怎,最后就是創(chuàng)建一個鏈接并將 blob 賦值進去生成文件穆刻。
記得添加請求頭 responseType:'blob'
總體邏輯:
var myFile = this.createFile(response.data);
let execlName = this.viewData.select.applyBisName + '_' + this.viewData.select.projectName + '_' + '項目申請表' + '.docx';
if(navigator.appVersion.toString().indexOf(".NET")>0){
window.navigator.msSaveBlob(myFile, execlName);
} else {
var a = document.createElement("a");
a.href =window.URL.createObjectURL(myFile);
a.download = execlName;
a.click();
document.body.appendChild(a);
}
數(shù)據(jù)轉(zhuǎn)換邏輯:
createFile(urlData) {
var bytes=window.atob(urlData),
n=bytes.length,
u8arr=new Uint8Array(n);
while(n--){
u8arr[n] = bytes.charCodeAt(n);
}
return new Blob([u8arr],{type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document'})
}