前端下载Excel 解决乱码问题

4,630 阅读1分钟

前端使用js 下载后端传过来的流文件

使用Axios下载Excel

const query = {"insId":"3","timeType":1,"startTime":'',"endTime":''}
axios({
  method: 'post',
  url: '你的后端接口链接',
  data: query,
  responseType: 'blob'
}).then(res => {
  console.log(res);
  if (res && res.data) {
    // 获取后台文件名称
    const disposition = res.headers['content-disposition']
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    const fileName = 'aa.xls'
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href)
    document.body.removeChild(link)
  }
})

原生xhr下载Excel 默认版

const query = {"insId":"3","timeType":1,"startTime":'',"endTime":''}

const xhr = new XMLHttpRequest();
xhr.open('POST', '你的后端接口链接', true);
xhr.setRequestHeader('content-type', 'application/json');
xhr.send(JSON.stringify(query))
xhr.responseType = "blob";
xhr.onload = () => {
  let elink = document.createElement("a");
  elink.download = new Date().getTime() + ".xls";
  elink.style.display = "none";
  const blob = new Blob([xhr.response]);
  elink.href = URL.createObjectURL(blob);
  document.body.appendChild(elink);
  elink.click();
  document.body.removeChild(elink);
}

xhr.send(null);

原生xhr下载Excel 设置参数版

<!DOCTYPE html>
<html lang="en">
<body>
  <script type="text/javascript">
    const query = {"insId":"3","timeType":1,"startTime":'',"endTime":''}
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '你的后端接口链接', true);
    // 打开注释会下载两次?
    // xhr.setRequestHeader('Accept', 'application/json,text/plain,*/*');
    xhr.setRequestHeader('content-type', 'application/json;charset=UTF-8');
    xhr.send(JSON.stringify(query))
    xhr.responseType = "blob";
    xhr.onload = () => {
      let elink = document.createElement("a");
      elink.download = new Date().getTime() + ".xls";
      elink.style.display = "none";
      // 此处需要注意 乱码问题 可能需要增加编码 但是我设置了 还是不行
      // let blob = new Blob(["\ufeff", xhr.response], { type: 'application/vnd.ms-excel' });
      const blob = new Blob([xhr.response], { type:'application/vnd.ms-excel' });
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    }

    xhr.send(null);
  </script>
</body>
</html>

后记

media-types官网中找到适合自己的设置后,我的就可以了。 image.png

仔细对比请求头和响应头

image.png

image.png