js 实现根据url下载文件

149 阅读1分钟

方式一

function downloadFile(fileUrl, fileName) {
    const a = document.createElement("a");
    a.download = fileName;
    a.href = fileUrl;
    a.click();
}
  • 简单快捷,但测试发现设置的fileName无效(我是在Chrome浏览器114版本上测试),无论设置中文还是英文最终都是文件保存时本身的名称,为了解决文件名命名的问题有以下方式实现

方式二

function downloadFile (fileUrl, fileName) {
  fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
      const a = document.createElement("a");
      const parseUrl = URL.createObjectURL(blob);
      a.href = parseUrl;
      a.download = fileName;

      // 在部分浏览器中,创建Blob链接后,需要延迟点击事件才能正常下载
      setTimeout(() => {
        a.click();
        URL.revokeObjectURL(parseUrl);
      }, 0);
    })
};
  • 上述方式使用fetch先请求到文件资源后使用blob进行下载,可以正常对文件名进行自定义