基本原理
流操作API中的ReadableStream 接口呈现了一个可读取的二进制流操作。Fetch API通过Response 的属性body 提供了一个具体的 ReadableStream 对象。
需要保存为UTF-8格式的UTF-8 的 BOM 的十六进制表示为 EF BB BF,也可以用一个Unicode字符表示:U+FEFF。所以我们只要在CSV或者Excel文件开头加入BOM就可以将文件保存为UTF-8 BOM格式。可以直接在Buffer中先加入\xEF\xBB\xBF作为开头,也可以在字符串开头加入\uFEFF这个Unicode字符。
const url = 'http://domain/download'
let filename = '';
Fetch.get(url)
.then(res => {
const contentDisposition = res.headers.get("content-disposition")
filename = contentDisposition.match(/filename="(.+)"/)[1]
const reader = res.body.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader.read().then( ({done, value}) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
push();
})
}
push();
}
});
})
.then(stream => {
return new Response(stream, { headers: { "Content-Type": "text/html" } }).text();
})
.then(result => {
const BOM = '\uFEFF';
const file = new Blob([BOM + result]);
const objectUrl = URL.createObjectURL(file)
const a = document.createElement("a")
document.body.appendChild(a)
a.style = "display: none"
a.href = objectUrl
a.download = filename
a.click()
window.URL.revokeObjectURL(objectUrl)
document.body.removeChild(a);
})
.catch(e => {
console.error(e);
});
},