首页 > 其他分享 >前端通过post下载文件,文件乱码的解决

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

时间:2023-02-16 17:25:03浏览次数:105  
标签:文件 url res 乱码 post document 下载

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

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

      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,一定要注释了它的引入否则它会过滤你返回的数据导致下载下来的文件是乱码

 

 

标签:文件,url,res,乱码,post,document,下载
From: https://www.cnblogs.com/wscw/p/17127458.html

相关文章