下午遇到一個(gè)業(yè)務(wù)場(chǎng)景衔峰,導(dǎo)出excel數(shù)據(jù)的接口辜纲。http 200 的時(shí)候判斷返回值滚澜,前端提示有沒(méi)有導(dǎo)出功能。因?yàn)槭窍螺d文件,所以我設(shè)置的 responseTy="arraybuffer"顶掉。這時(shí)候就出問(wèn)題了,如果后端給我的不是文件挑胸,是異常信息痒筒,我識(shí)別不了。所以就需要有 ArrayBuffer 轉(zhuǎn)換成 String 的需求
涉及到的環(huán)境
- axios
- ArrayBuffer
在網(wǎng)上查找了下茬贵, 發(fā)現(xiàn)大部分的都是對(duì) ArrayBuffer 的說(shuō)明簿透,沒(méi)有涉及到轉(zhuǎn)換的事情
--------------------------- padding----------------------------
最終代碼
/**
* 將 ArrayBuffer 轉(zhuǎn)換成 String
* @param {*} arrayBuffer
*/
const decodeUtf8 = (arrayBuffer) => {
var result = "";
var i = 0;
var c = 0;
var c1 = 0;
var c2 = 0;
var c3 = 0;
var data = new Uint8Array(arrayBuffer);
// If we have a BOM skip it
if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
i = 3;
}
while (i < data.length) {
c = data[i];
if (c < 128) {
result += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
if (i + 1 >= data.length) {
throw "UTF-8 Decode failed. Two byte character was truncated.";
}
c2 = data[i + 1];
result += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
if (i + 2 >= data.length) {
throw "UTF-8 Decode failed. Multi byte character was truncated.";
}
c2 = data[i + 1];
c3 = data[i + 2];
result += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return result;
}
/**
* 導(dǎo)出文件
* @param {Object}
* data:Object 參數(shù)
* url: String 地址
* method: String
* fileName: String 文件名稱
*/
function DownloadFileBinary({ data, url, method = "POST", fileName = '下載文件' }) {
axios({
method,
url,
data,
responseType: "arraybuffer"
})
.then(res => {
// 將arraybuffer to json
let str = decodeUtf8(res);
let json = JSON.parse(str);
if (!json.state) {
Message({
type: "error",
message: json.message
});
return false;
}
console.log(res, "-----------------");
let blob = new Blob([res], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
if (window.navigator.msSaveBlob) {
// for ie 10 and later
try {
let url = fileName;
console.log(url); // IE 需要引用一下才能獲取變量的值
window.navigator.msSaveBlob(blob, url);
} catch (e) {
console.error(e);
}
} else {
// let objecturl = URL.createObjectURL(blob);
// window.location.href = objecturl;
let link = document.createElement("a");
document.querySelector("body").appendChild(link);
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
document.querySelector("body").removeChild(link);
}
})
.catch(err => {
});
},