使用fetch访问跨域静态资源并下载

71 阅读1分钟
      fetch(item.attachmentUrl, {
          method: 'GET',
          mode: 'cors', // 使用 CORS 模式
      })
      .then(response => response.blob())
      .then(blob => {
          // 处理返回的二进制数据
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = item.attachmentName; // 设置下载的文件名
        document.body.appendChild(a); // 将 <a> 元素添加到 DOM 中
        a.click(); // 触发下载
        document.body.removeChild(a); // 下载完成后移除 <a> 元素
        URL.revokeObjectURL(url); // 释放 URL 对象
      })
      .catch(error => {
          console.error('Fetch error:', error);
      });