js实现下载文件

js实现下载文件

【downloadUtils.js】

//方案1:根据url下载文件(经测试这种方案无法重命名文件!!!)
export function downloadByUrl(url, filename) {
  const link = document.createElement("a");
  link.style.display = "none";
  // 设置下载地址
  link.setAttribute("href", url);
  // 设置文件名
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

//方案2:使用 blob 数据类型方式(推荐)
export function downloadByBlob(downloadUrl, downloadFileName) {
  getBlob(downloadUrl).then((blob) => {
    saveAs(blob, downloadFileName);
  });
}

function getBlob(url) {
  return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        } else {
          reject(new Error(`Request failed with status ${xhr.status}`));
        }
      };
      xhr.onerror = () => {
        reject(new Error("Request failed"));
      };
      xhr.send();
    })
}

function saveAs(blob, filename) {
  const link = document.createElement("a");
  const body = document.body;

  link.href = window.URL.createObjectURL(blob);
  link.download = filename;

  // hide the link
  link.style.display = "none";
  body.appendChild(link); //解决火狐无法触发

  link.click();
  body.removeChild(link);

  window.URL.revokeObjectURL(link.href);
}

参考

JS通过URL下载文件并重命名两种方式代码

本文为 程序员青阳 原创文章,遵循 CC BY-NC-SA 4.0 版权协议,转载请附上原文链接及本声明。

原文链接:https://heliufang.github.io/posts/6e9a6903/index.html