根据文件扩展名导出文件

新建一个a标签,根据后台返回数据赋值给href,然后触发点击a事件。
exportData(id) {
  axios
    .get(config.DOWNLOAD_FILE + "/" + id, {
      //url: 接口地址
      responseType: `arraybuffer`, //一定要写
      headers: {
        Authorization: getToken(),
        "Content-Type": "application/octet-stream"
      }
    })
    .then(res => {
      if (res.status == 200) {
        let blob = new Blob([res.data], {
          type: `application/octet-stream` 
        });
        let objectUrl = URL.createObjectURL(blob);
        let link = document.createElement("a");
        var tempName = res.headers["content-disposition"];
        // var str = tempName.match(/filename=(\S*)/)[1];
        var str = tempName.split("filename=")[1];
        let fname = str; //下载文件的名字
        link.href = objectUrl;
        link.setAttribute("download", fname);
        document.body.appendChild(link);
        link.click();
      } else {
        this.$message({
          type: "warning",
          message: "Download failed"
        });
      }
    });
}

猜你喜欢

转载自blog.csdn.net/xuerwang/article/details/88026782