Skip to content

网络请求-3-fetch 下载进度 勘误 #1246

Open
@frankli0324

Description

@frankli0324

原文链接: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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions