后端返回文件流

21 阅读1分钟

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

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

function downloadFile(obj, name, suffix) {
  const url = window.URL.createObjectURL(new Blob([obj]));
  const link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  const fileName = parseTime(new Date()) + "-" + name + "." + suffix;
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(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 (res.ok) {
            /* 返回的是文件 */
            if (res.headers.has('Content-Disposition')) {
              fileName = decodeURIComponent(res.headers.get('Content-Disposition') || '');
              return res.blob();
            }
            return res.json();
          } else {
            return null;
          }
        })
        .then(data => {
          if (data) {
            if (data.code === 500) {
              notification.error({
                message: '请求错误',
                description: data.message,
              });
              return 'fail';
            } else {
              const a = document.createElement('a');
              a.style.display = 'none';
              a.href = window.URL.createObjectURL(data);
              let url: string = (fileName && fileName.split(';')[1]) || '';
              url = url
                .split('=')
                .slice(1)
                .join('');
              a.download = url;
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              window.URL.revokeObjectURL(a.href);
              return 'suc';
            }
          }
          return null;
        });
}