js导出文件的两种方式

              //创建a标签防止被浏览器拦截
              var a = document.createElement("a");
              a.setAttribute(
                "href",
                "/static/file/export/" + response.data.data
              );
              a.setAttribute("target", "_blank");
              a.click();            

模拟a标签点击,会打开一个新的页面一闪而过获取文件。指向文件地址。

 const filename = response.headers["content-disposition"]
                .split("filename=")[1]
                .split("; filename")[0];
              const url = window.URL.createObjectURL(response.data);
              const link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              link.setAttribute("download", filename);
              document.body.appendChild(link);
              link.click();

获取到文件流信息,前端处理获取文件,不会打开新的页面。

posted @ 2022-03-14 12:12  Dark华  阅读(2295)  评论(0编辑  收藏  举报