【通过Fetch请求下载文件】计算下载进度

405 阅读1分钟

要获取 Fetch 请求的进度,可以使用 fetch 函数返回的 Response 对象的 body 属性,并使用 Response.body.getReader() 方法创建一个 ReadableStream,然后通过读取该流来获取数据的进度信息。

要获取 Fetch 请求的进度,可以使用 `fetch` 函数返回的 `Response` 对象的 `body` 属性,并使用 `Response.body.getReader()` 方法创建一个 `ReadableStream`,然后通过读取该流来获取数据的进度信息。


downloadWithProgress(url, progress) {
    return new Promise((resolve, reject) => {
      fetch(url, { method: 'GET' })
        .then(response => {
          if (!response.ok) {
            this.$message.error("请求失败");
          }
          const contentLength = response.headers.get('Content-Length');
          const totalBytes = parseInt(contentLength, 10);
          let loadedBytes = 0;
          const reader = response.body.getReader();
          let chunks = [];

          function read() {
            reader.read().then(({ done, value }) => {
              if (done || totalBytes === 0) { //空文件直接返回
                const blob = new Blob(chunks);
                resolve(blob);
                progress(100);
                return;
              }
              loadedBytes += value.length;
              const process = Math.round((loadedBytes / totalBytes) * 100);
              if (process < 100 && process % 10 === 0) {
                progress(process); //进度以10为单位进行更新
              }
              chunks.push(value);
              read();
            }).catch(error => {
              reject(error);
            });
          }
          read();
        }).catch(e => {
          err(e);
        });
    });
  }

// 调用示例
const url = 'https://example.com/myfile.zip';
downloadWithProgress(url,progress=>{console.log(progress)})