后端返回文件流

时间:2025-03-28 10:19:20

记得请求时加上
method: “get”,
responseType:‘blob’, // 这里很重要

把拿到的流传进下面的方法

function downloadFile(obj, name, suffix) {
  const url = (new Blob([obj]));
  const link = ("a");
   = "none";
   = url;
  const fileName = parseTime(new Date()) + "-" + name + "." + suffix;
  ("download", fileName);
  (link);
  ();
  (link);
}
export async function batchExport(ids: string) {
    let fileName: string = '';
    fetch(`${BASE_URL}/transport/export/xxx?ids=${ids}`, {
        method: 'POST',
        credentials: 'include',
        // headers: { responseType: 'arraybuffer' },
        // body: formDt,
      })
        .then(res => {
          if () {
            /* 返回的是文件 */
            if (('Content-Disposition')) {
              fileName = decodeURIComponent(('Content-Disposition') || '');
              return ();
            }
            return ();
          } else {
            return null;
          }
        })
        .then(data => {
          if (data) {
            if ( === 500) {
              ({
                message: '请求错误',
                description: ,
              });
              return 'fail';
            } else {
              const a = ('a');
               = 'none';
               = (data);
              let url: string = (fileName && (';')[1]) || '';
              url = url
                .split('=')
                .slice(1)
                .join('');
               = url;
              (a);
              ();
              (a);
              ();
              return 'suc';
            }
          }
          return null;
        });
}