概述流式压缩上传能降低带宽。本文给出将文件管道接入压缩再作为请求体的实现。流式管道上传function streamFromFile(file, size = 1024*1024) {
let o = 0; return new ReadableStream({ async pull(controller) { if (o >= file.size) { controller.close(); return; } const b = file.slice(o, o+size); const ab = await b.arrayBuffer(); controller.enqueue(new Uint8Array(ab)); o+=size; } });
}
async function uploadGzip(url, file) {
const cs = new CompressionStream('gzip');
const body = streamFromFile(file).pipeThrough(cs);
const res = await fetch(url, { method:'POST', headers:{ 'Content-Encoding':'gzip' }, body });
if (!res.ok) throw new Error('upload failed');
}

发表评论 取消回复