前端通过new Blob下载文档流(下载zip或excel)

当后端返回这样的预览:

前端该如何下载呢?首先在axios请求里,加入第三个参数{ responseType: 'blob' }。

复制代码
proxy.$post(url, params, { responseType: 'blob' }).then((res)=>{
  downloadFormat(res)
});

然后在一个函数里处理返回,创建a标签来下载

复制代码
// 这里是下载zip文件的处理

const downloadFormat = (res) => {
  if (!res.data) {
    return;
  }
  let stringName = res.headers['content-disposition'].split(';')[1];// 一般来说,文件名字后端都在返回头里,前后端可以约定文件名前用 @ 符号分隔,便于取值,用其他符号也可以。
  let fileName = stringName.split('=')[1];// 获取到了后缀名
  const blob = new Blob([res.data], { type: 'application/zip' }); // application/zip就是设置下载类型,需要设置什么类型可在标题二处查看,
  const url = window.URL.createObjectURL(blob); // 设置路径
  const link = window.document.createElement('a'); // 创建a标签
  link.href = url;
  link.setAttribute('download', fileName); // 给下载后的文件命名
  link.style.display = 'none';
  link.click();
  URL.revokeObjectURL(url); // 释放内存
}

// 这里是下载excel的处理, 可根据需要传文件名和文件类型

const downloadFormat = (res, fileName, fileType) => {

  let stringName = res.headers['content-disposition'].split(';')[1];
  let fileName = stringName.split('=')[1];

  const blob = new Blob([res.data], { type: fileType ?? 'application/vnd.ms-excel' });

  // application/vnd.ms-excel 表示.xls文件
  // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 表示.xlsx文件
  
  // 也可以不写type,反正是下载,又不是上传。

  if (!blob) {
    return;
  }

  const url = window.URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', fileName);

  document.body.appendChild(link);
  link.click();
  window.URL.revokeObjectURL(url); // 为了性能和内存使用状况,应该在适当的时候释放url
}

还有一种get方式通过window.location.href来下载文件,在浏览器F12网络里预览和响应没有返回值,写法如下

复制代码
window.location.href = '/api/exportData?ids=' + 拼接的参数

其中/api被代理转发了,在vite.config.js文件里config.server.proxy对象配置如下:

"/api": {
  target: "https://test.XXX.net",
  secure: false,
  changeOrigin: true,
}

// 真实请求地址含api,并未被reWrite为空
相关推荐
Java展博12 小时前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户1129361121912 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼13 小时前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_41913 小时前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
去伪存真14 小时前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li15 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写15 小时前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端
TDengine (老段)16 小时前
TDengine IDMP 知识库与知识图谱
大数据·前端·物联网·知识图谱·时序数据库·tdengine·涛思数据
goehou17 小时前
PNG 转 WebP 不一定变小,我量了三类图
前端·性能优化·webp·sharp
夕水18 小时前
一个小小的颜色选择器,差点让我开发出一个组件库来
前端·javascript·typescript