公告
淡泊明志,宁静致远
网站资讯
本站文章字数合计
267.4k
本站Hexo版本
6.1.0
本站Node版本
20.19.6
本站已运行时间
最后更新时间
本文目录
已阅读:%

分类: web前端 | 标签: js

js实现下载文件

发表于: 2024-02-19 14:05:12 | 字数统计: 263 | 阅读时长预计: 1分钟

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下载文件并重命名两种方式代码

------ 本文结束,感谢您的阅读 ------
本文作者: 程序员青阳
版权声明: 本文采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。