字符串–》arrayBuffer
function stringToArrayBuffer(str) { // utf16 不管是字符还是汉字
let buffer = new ArrayBuffer(str.length * 2);
let view = new Uint16Array(buffer)
for (let i = 0; i < str.length; i++) {
view[i] = str.charCodeAt(i)
}
return buffer
}
arrayBuffer–》string
function ArrayBufferToString(buf) {
return String.fromCharCode(...new Uint16Array(buf))
}
function request(url, method = "get") {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
resolve(xhr.response);
}
xhr.send();
})
}
request('/download').then(arraybuffer => {
let b = new Blob([arraybuffer]);
let blobUrl = URL.createObjectURL(b);
let a = document.createElement('a');
a.href = blobUrl;
a.download = 'a.pdf';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(blobUrl)
})