前端通过post下载文件,文件乱码的解决

有时候数据量大或者需要上传文件,但接口又必须返回一个下载的流,就必须前端设置一下进行下载

过程也很简单 网上一搜一大堆博客,标红的地方必须这样写 其余的可以根据你的需求进行修改

      var formdata = new FormData();
      this.$http({
        method: "POST",
        url: url,
        responseType: "blob", 
        data: formdata,
      }).then((res) => {
        if (res) {
          this.downloadFile(res);
      }  

   downloadFile(res) {
      let url = window.URL.createObjectURL(new Blob([res.data],{type: res.headers['content-type']}));
      let a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      a.setAttribute("download", `账号密码.xls`);
      document.body.appendChild(a);
      a.click();
      url = window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }
 

但我遇到的下载后文件都是乱码,研究了半天发现项目中有 mock.js,一定要注释了它的引入否则它会过滤你返回的数据导致下载下来的文件是乱码

 

 

posted @ 2023-02-16 17:10  曹伟666  阅读(518)  评论(0编辑  收藏  举报