前端下载二进制文件以及解决从content-disposition获取文件名中文乱码问题

2,537 阅读1分钟

这种情况一般就是实际项目使用的ajax请求接口方式,比如post请求,前端传递若干参数,后端返回文件二进制流。

首先把axios配置项返回结果为二进制格式

axios({  
  method: 'post',  
  url: "http://localhost:3000/download",  
  data: {    
    test: "test data"  
  },  
  responseType: "blob" 
})

  • 拿到返回数据后,将二进制数据生成一个文件url,用URL.createObjectURL生成url时需要传入Blob类型的参数。

  • 生成了url后就是模拟a标签来下载。

.then((res) => {
              if (res) {
                let temp = res.headers["content-disposition"]
                  .split(";")[1]
                  .split("=")[1];
                   //对文件名乱码转义--【Node.js】使用iconv-lite解决中文乱码
                let iconv = require("iconv-lite");
                let fileName = iconv.decode(temp, "gbk");
                let type = decodeURIComponent(res.headers["content-type"]); // const xlsx = 'application/vnd.ms-excel'
                // console.log(type);
                const blob = new Blob([res.data], {
                  type: "application/vnd.ms-excel;charset=UTF-8",
                });
                // console.log(blob);
                const blobUrl = window.URL.createObjectURL(blob);
                let a = document.createElement("a"); // 转换完成,创建一个a标签用于下载
                // 设置href属性为文件路径,download属性可以设置文件名称 
                  a .style.display = 'none'
                a.href = blobUrl;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                Window.URL.revokeObjectURL(blobUrl);
                a.remove();
              } else {
                this.$message.error("导出失败");
              }
            });