2020-12-27个人总结

vue中使用axios下载excel二进制文件 出现乱码问题的解决方法?

首先,先排查问题。

  1. 就是请求返回的类型是不是(或者有没有这个)responseType: "blob"。
  2. 在main.js中是否引入了和axios有冲突的插件,我当时就是因为引入了 mock, 所以这么多次都一直是乱码。
  3. 最后如果还是不行的话可以尝试修改 let blob = new Blob([res], {type: "application/vnd.ms-excel"}); res就是后端返回的二进制文件流。
    代码如下:
  testExport({ 传递的参数 })
        .then((res) => {
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
          });
          const fileName = "下载测试文件.xls";
          const alink = document.createElement("a");
          alink.download = fileName;
          alink.style.display = "none";
          alink.href = URL.createObjectURL(blob); // 这里是将文件流转化为一个文件地址
          document.body.appendChild(alink);
          alink.click();
          URL.revokeObjectURL(alink.href); // 释放URL 对象
          document.body.removeChild(alink);
        })
        .catch((error) => {
          this.$notify({
            type: "error",
            title: "网络错误,请重新查询",
            message: error,
            position: "bottom-right",
          });
        })
// 封装的请求
export function testExport(data) {
  return HTTP_FUNCTION({
    url: HTTP_URL.test.export,
    method: "post",
    data,
    responseType: "blob",
  });
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容