下午遇到一个业务场景,导出excel数据的接口。http 200 的时候判断返回值,前端提示有没有导出功能。因为是下载文件,所以我设置的 responseTy="arraybuffer"。这时候就出问题了,如果后端给我的不是文件,是异常信息,我识别不了。所以就需要有 ArrayBuffer 转换成 String 的需求
涉及到的环境
- axios
- ArrayBuffer
在网上查找了下, 发现大部分的都是对 ArrayBuffer 的说明,没有涉及到转换的事情
--------------------------- padding----------------------------
最终代码
/**
* 将 ArrayBuffer 转换成 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;
}
/**
* 导出文件
* @param {Object}
* data:Object 参数
* 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 => {
});
},
网友评论