下载文件的方式有多种,以下是其中一种实现方式:

  1. 使用 XMLHttpRequest 发送请求,并设置 responseType 为 'blob'。
  2. 在请求成功后,将响应的数据(blob 对象)转换成 URL,通过创建 a 标签并设置 href 和 download 属性,模拟用户点击下载链接。
  3. 将 a 标签添加到文档中,并通过 click() 方法触发点击事件,完成下载。

示例代码如下:

function downloadFile(url) {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function() {
    if (this.status === 200) {
      let blob = this.response;
      let url = URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.href = url;
      a.download = 'file.pdf';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };
  xhr.send();
}

调用方式:

downloadFile('http://example.com/file.pdf');

原文地址: https://www.cveoy.top/t/topic/mWXu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录