javascript-tutorial / javascript-tutorial/zh.javascript.info
网络请求-3-fetch 下载进度 勘误
- Lingua principale
- HTML
- Stelle
- 10.8k
- Fork
- 1.2k
- Metriche di merge delle PR
- Nessuna PR unita negli ultimi 30g
Descrizione
原文链接:https://zh.javascript.info/fetch-progress
在Content-Encoding指定了某种压缩方式时,fetch提供的getReader中读取到的是解压缩*后*的二进制流,而Content-Length所指示的是解压缩前的请求体大小。
在绝大多数场景,浏览器自动指示Accept-Encoding的情况下,不能直接使用Content-Length作为完整报文长度进行进度计算,而应当使用其它方式/响应头告知客户端完整的报文长度。
原文中示例代码如下:
```js
// 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}`)
}
// 以下略
```
Guida per i contributori
Nessuna guida per i contributori indicizzata per questo repository
Direzione di ricerca
Start with the fetch progress article at https://zh.javascript.info/fetch-progress and review the example using response.body.getReader(), Content-Length, and receivedLength. Correct the explanation or example so it accounts for compressed responses, and confirm that the documented progress calculation matches the byte stream returned by fetch.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript
- Ambito
- documentation
- Tipo di issue
- Documentazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 45/100