Vue front end downloads files across domains

In general, the download attribute of the a tag can be used to download files, provided that it is under the same-origin policy. In order to solve the cross-domain problem, we use js to get the blob type file and download the remote file to the local

Paste the code directly

    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();
    }

Guess you like

Origin blog.csdn.net/a0405221/article/details/112211466