通过地址下载文件 【 前提不能跨域 】 【目前使用,处理pdf、txt文件 a标签下载 自动预览】

74 阅读1分钟
/**
 * 通过地址下载文件 【 前提不能跨域 】 【目前使用,处理pdf、txt文件 a标签下载 自动预览】
 * @param {*} fileUrl 文件地址
 * @param {*} fileName 文件名 默认为文件地址的文件名
 *  */
 function downloadFilebByUrl(fileUrl, fileName) {
  fetch(fileUrl)
    .then((response) => response.blob())
    .then((blob) => {
      const url = window.URL.createObjectURL(new Blob([blob]));

      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      // a.download = fileName || 'document.pdf';
      a.download = fileName || fileUrl.split('/').pop();

      document.body.appendChild(a);

      a.click();

      window.URL.revokeObjectURL(url);
    })
    .catch((error) => {
      console.error('下载 PDF 时出错:', error);
    });
}