0


前端通过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];// 获取到了后缀名
  let 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) => {
  if (!blob) {
    return;
  }
  const url = window.URL.createObjectURL(
    new Blob([blob], { type: fileType ?? 'application/vnd.ms-excel' })
  );

  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为空

本文转载自: https://blog.csdn.net/qq_33548028/article/details/137887197
版权归原作者 热情的蟋蟀 所有, 如有侵权,请联系我们删除。

“前端通过new Blob下载文档流(下载zip或excel)”的评论:

还没有评论