Open
Description
原文链接:https://zh.javascript.info/fetch-progress
在Content-Encoding指定了某种压缩方式时,fetch提供的getReader中读取到的是解压缩后的二进制流,而Content-Length所指示的是解压缩前的请求体大小。
在绝大多数场景,浏览器自动指示Accept-Encoding的情况下,不能直接使用Content-Length作为完整报文长度进行进度计算,而应当使用其它方式/响应头告知客户端完整的报文长度。
原文中示例代码如下:
// Step 1:启动 fetch,并获得一个 reader
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');
const reader = response.body.getReader();
// Step 2:获得总长度(length)
const contentLength = +response.headers.get('Content-Length');
// Step 3:读取数据
let receivedLength = 0; // 当前接收到了这么多字节
let chunks = []; // 接收到的二进制块的数组(包括 body)
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} of ${contentLength}`)
}
// 以下略
Metadata
Metadata
Assignees
Labels
No labels