You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript Fetch API限制下载字节数后重复调用失效问题求助

问题原因

第一次调用后,浏览器会自动缓存该URL的完整响应。第二次调用fetch时,默认会直接读取本地缓存的完整数据,这时候调用reader.cancel()已经无法终止缓存数据的读取流程,导致代码无法正常工作。

解决方案

在fetch请求中添加缓存控制配置,强制浏览器不使用缓存,每次都发起新的网络请求:

修改fetch的调用代码,添加cache: 'no-store'参数:

const response = await fetch(url, { cache: 'no-store' });
修改后的完整代码
async function download(url, maxBytes) {
  try {
    // 添加缓存控制,强制不使用缓存
    const response = await fetch(url, { cache: 'no-store' });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const reader = response.body.getReader();
    let bytesRead = 0;
    let chunks = [];
    while (bytesRead < maxBytes) {
      const { done, value } = await reader.read();
      if (done) { break; }
      chunks.push(value);
      bytesRead += value.length;
    }
    reader.cancel("Download size limit reached.");

    const result = new Uint8Array(bytesRead);
    let offset = 0;

    for (const chunk of chunks) {
      result.set(chunk, offset);
      offset += chunk.length;
    }

    let str = (new TextDecoder().decode(result));
    // 这里处理读取到的字符串
  } catch (error) {
    console.error('Error downloading the file:', error);
  }
}

download('https://speed.hetzner.de/1GB.bin', 2000000); 
补充说明
  • cache: 'no-store'会完全禁用缓存,每次请求都走网络,适合我们这种不需要完整响应缓存的场景。
  • 如果想要弱缓存(比如验证缓存是否有效),可以改用cache: 'no-cache',但对于终止部分下载的需求,no-store更直接有效。

内容的提问来源于stack exchange,提问作者fres

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 06:01:06