vue 前端跨域下载文件

一般情况下用a标签的download属性可以下载文件, 前提是在同源策略下。为了解决跨域问题我们用js获取blob类型文件,将远程文件下载到本地

直接贴代码

    downloadFile(url) {
    
    
      url = url.replace(/\\/g, "/");
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      // 文件下载进度
      xhr.onprogress = (res) => {
    
    
        this.loadingTip =
          "源文件下载中: " + ((res.loaded / res.total) * 100).toFixed(2) + "%";
      };
      xhr.onload = () => {
    
    
        this.loadingTip = "";
        this.loading = false;

        if (xhr.status === 200) {
    
    
          // 获取文件blob数据并保存
          var num = url.lastIndexOf("/") + 1;
          //把参数和文件名分割开
          var fileName = url.substring(num).split("?")[0];
          var export_blob = new Blob([xhr.response]);
          var save_link = document.createElementNS(
            "http://www.w3.org/1999/xhtml",
            "a"
          );
          save_link.href = URL.createObjectURL(export_blob);
          save_link.download = fileName;
          save_link.click();
        }
      };
      this.loading = true;
      xhr.send();
    }

猜你喜欢

转载自blog.csdn.net/a0405221/article/details/112211466