fetch 请求下载跨域

fetch直接请求下载错误,加上{mode: 'cors'} 这样后端可以获取到数据请求正常,这样后端也得设置access-control-allow-origin:* 或者指定前端域名
 
fetch("https://img0.baidu.com/it/u=1207788134,3297174930&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=645",{mode: 'cors'})
    .then((response) => {
      // 从响应头获取文件名
      const contentDisposition = response.headers.get('content-disposition');
      let fileName = '';
      if (contentDisposition) {
        const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
        if (matches != null && matches[1]) {
          fileName = matches[1].replace(/['"]/g, '');
        }
      }
      return response.blob().then((blob) => ({ blob, fileName }));
    })
    .then(({ blob, fileName }) => {
      // 创建 Blob URL
      const blobUrl = window.URL.createObjectURL(blob);

      // 创建临时链接并触发下载
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = blobUrl;
      link.download =  fileName || 'download'; // 使用文件名或默认名
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(blobUrl);
    })
    .catch((error) => {
      console.error('下载失败:', error);
    });

 

posted @ 2025-06-20 14:17  风花一世月  阅读(80)  评论(0)    收藏  举报