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

如何让axios-cache-adapter缓存responseType为blob的文件下载请求

问题原因

axios-cache-adapter 默认内置的响应排除规则会自动过滤掉responseType不为空、json、text三种类型的请求,Blob属于二进制响应类型,会被默认排除在缓存范围外,这就是你设置responseType: 'blob'的请求无法缓存的核心原因。
另外你当前代码中每次调用下载接口都会重新生成axios实例和缓存存储实例,缓存无法跨请求复用,也会导致缓存失效。

解决方法

1. 自定义缓存排除规则,放开Blob类型限制

修改setup方法中的cache配置,添加自定义exclude判断逻辑,同时因为IndexedDB/LocalForage本身支持直接存储Blob对象,不需要额外做序列化转换,只要放开排除规则即可。

2. 单例化axios缓存实例

避免每次请求都重新生成实例,保证缓存存储是全局复用的。

修改后的完整代码

// set axios defaults
axios.defaults.headers.common = {
  'Authorization': `Bearer ${accessToken}`,
  'Content-Type': 'application/json'
};

// 缓存axios实例,避免重复生成
let apiInstance = null;

const configureAxios = async () => {
  // 已生成实例直接返回
  if (apiInstance) return apiInstance;

  await localforage.defineDriver(memoryDriver);

  const forageStore = localforage.createInstance({
    driver: [
      localforage.INDEXEDDB,
      localforage.LOCALSTORAGE,
      memoryDriver._driver
    ],
    name: 'my-cache'
  });

  apiInstance = setup({
    // `axios-cache-adapter` options
    cache: {
      maxAge: 15 * 60 * 1000,
      exclude: {
        query: false,
        // 自定义判断逻辑,不要排除blob类型的请求
        filter: (req) => {
          // 返回true代表排除不缓存,返回false代表需要缓存
          // 这里示例只缓存GET请求,你可以根据自身需求调整规则
          return req.method !== 'get';
        }
      },
      store: forageStore,
      // 可选:如果不需要根据响应头判断缓存时效可以关闭,避免blob响应头解析问题
      readHeaders: false
    }
  });
  return apiInstance;
};

// call this function in JSX Component to download file
export const downloadFile = async (fileId) => {
  const api = await configureAxios();

  const response = await api.get(`api/download/${fileId}`, {
    responseType: 'blob',
  });

  return response.data; // returns file data
};
验证说明

修改后调用两次同一个fileId的下载请求,第二次请求不会触发网络请求,直接从缓存中返回Blob数据,即可确认配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:15:02