前端实现文件下载的方法

//下载文件
function downLoad(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function () {
    var blob = this.response;
    const fileName = url.split("/")[url.split("/").length - 1]; // 导出文件名
    let a = document.createElement("a");
    a.download = fileName;
    a.style.display = "none";
    a.href = window.URL.createObjectURL(blob);
    a.target = "_blank";
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(a.href); // 释放URL 对象
    document.body.removeChild(a); // 删除 a 标签
  };
  xhr.send();
}

 

posted @ 2021-04-22 11:06  潇潇mini  阅读(177)  评论(0编辑  收藏  举报