【fetch 上传和下载进度】

最近看到一个代码 记录fetch 上传和下载进度的代码 忍不住记录下

async function main() {
    const blob = new Blob([new Uint8Array(10 * 1024 * 1024)]); // any Blob, including a File
    const uploadProgress = document.getElementById("upload-progress");
    const downloadProgress = document.getElementById("download-progress");
  
    const totalBytes = blob.size;
    let bytesUploaded = 0;
  
    // Use a custom TransformStream to track upload progress
    const progressTrackingStream = new TransformStream({
      transform(chunk, controller) {
        controller.enqueue(chunk);
        bytesUploaded += chunk.byteLength;
        console.log("upload progress:", bytesUploaded / totalBytes);
        uploadProgress.value = bytesUploaded / totalBytes;
      },
      flush(controller) {
        console.log("completed stream");
      },
    });
    const response = await fetch("https://httpbin.org/put", {
      method: "PUT",
      headers: {
        "Content-Type": "application/octet-stream"
      },
      body: blob.stream().pipeThrough(progressTrackingStream),
      duplex: "half",
    });
    
    // After the initial response headers have been received, display download progress for the response body
    let success = true;
    const totalDownloadBytes = response.headers.get("content-length");
    let bytesDownloaded = 0;
    const reader = response.body.getReader();
    while (true) {
      try {
        const { value, done } = await reader.read();
        if (done) {
          break;
        }
        bytesDownloaded += value.length;
        if (totalDownloadBytes != undefined) {
          console.log("download progress:", bytesDownloaded / totalDownloadBytes);
          downloadProgress.value = bytesDownloaded / totalDownloadBytes;
        } else {
          console.log("download progress:", bytesDownloaded, ", unknown total");
        }
      } catch (error) {
        console.error("error:", error);
        success = false;
        break;
      }
    }
    
    console.log("success:", success);
  }
  main().catch(console.error);

需要注意的是有一定兼容性问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值