1.原理
需要显示下载进度per,就要知道文件的长度len和目前的进度pro,per = pro / len
len:文件的长度通过返回值中的response.headers.get('Content-Length')
pro:
主要使用fetch的response.body属性,它是ReadableStream的一个特殊对象,可以逐块(chunk)提供body,即是将一次返回的数据按块返回
我们可以使用它实现对进度读取的完全控制,以用来计当前下载进去
2.Step
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
let response = await fetch(''); const reader = response.body.getReader();
const len = +response.headers.get('Content-Length');
let pro = 0; let chunks = []; while(true) { const {done, value} = await reader.read(); if (done) { break; } chunks.push(value); pro += value.length; console.log(`Received ${pro} of ${len}`) }
let chunksAll = new Uint8Array(pro); let position = 0; for(let chunk of chunks) { chunksAll.set(chunk, position); position += chunk.length; }
let result = new TextDecoder("utf-8").decode(chunksAll);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| fetch( "url", { method: "POST", body: JSON.stringify{{}}, dataType: "text" } ).then((response) => { const reader = response.body.getReader(); while(true) { const {done, value} = await reader.read(); if (done) { break; } console.log(`Received ${value.length} bytes`) } })
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| fetch( "url", { method: "POST", body: JSON.stringify{{}}, dataType: "text" } ).then((response) => { const reader = response.body.getReader(); while(true) { const {done, value} = await reader.read(); if (done) { break; } console.log(`Received ${value.length} bytes`) } })
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100'); const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0; let chunks = []; while(true) { const {done, value} = await reader.read(); if (done) { break; } chunks.push(value); receivedLength += value.length; console.log(`Received ${receivedLength} of ${contentLength}`) }
let chunksAll = new Uint8Array(receivedLength); let position = 0; for(let chunk of chunks) { chunksAll.set(chunk, position); position += chunk.length; }
let result = new TextDecoder("utf-8").decode(chunksAll);
let commits = JSON.parse(result);
|