最近遇到一个下载文件的需求,不是请求后端接口直接下载文件,而是后端返回blob格式的文件,前端自行下载文件
下面的具体的操作代码
1、修改request请求(请求是封装好的axios方法),增加响应参数 responseType: ‘blob’
exportApi: () => {
  return request({
    url: '/export',
    method: 'post',
    responseType: 'blob'
  });
}
2、下载excel方法,下面是简单封装的通用方法
function downloadFile(res: any, filename?: any) {
  const a = document.createElement('a');
  // 该实例化的方式第一个参数必须是数组的格式
  const blob = new Blob([res], {
    type: "application/vnd.ms-excel"
  });
  const url = window.URL.createObjectURL(blob);

  a.setAttribute('href', url);
  a.setAttribute("download", filename);
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐