You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已解决:如何在React客户端打开流式PDF文件

如何在React中读取后端返回的PDF并在新标签页打开?

从后端获取PDF文件时得到如下二进制数据:

%PDF-1.7 %���� 5 0 obj <<Filter/FlateDecode/Length 823>>stream x���MS�0���{l���)&���#CCK'!%�ӿߕmb���;�y�Ҿ��K��H�����aN��q��%�Iz&@�i�T
<......>
1950
%EOF

注:调用后端接口时在Postman中可以正常查看PDF内容。

尝试过的代码

后端控制器(NestJS)

@Get('/getPDF/:uuid')
async getFile(
  @Param('uuid') uuid: string,
  @Response({ passthrough: true }) res,
): Promise<StreamableFile> {
  const resp = await this.service.downloadPDF(uuid);

  if (!resp) {
    return null;
  }

  res.header('Content-Type', `application/pdf`);
  res.header('Content-Disposition', `attachment; filename="${resp.fileName}`);
  return new StreamableFile(resp.buffer); // resp.buffer === Uint8Array
}

前端(React)

API调用代码

getPDF(uuid: string): Promise<AxiosResponse<Blob>> {
  return this.httpClient.get(`${this.apiUrlPath}/getPDF/${uuid}`, {
    responseType: 'blob',
  });
}

渲染PDF代码

const response = await api.getPDF(uuid);
window.open(URL.createObjectURL(response.data));

遇到的错误

TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.


解决方案

将AxiosResponse的类型从Blob改为ArrayBuffer,并通过该缓冲区创建新的Blob即可解决问题。

可行代码

更新后的API调用代码

getPDF(uuid: string): Promise<AxiosResponse<ArrayBuffer>> {
  return this.httpClient.get(`${this.apiUrlPath}/getPDF/${uuid}`, {
    responseType: 'arraybuffer',
  });
}

更新后的渲染PDF代码

const response = await api.getPDF(uuid);
const blob = new Blob([response.data], { type: "application/pdf" });
window.open(URL.createObjectURL(blob));

感谢amir sarfar提供的解决方案


内容的提问来源于stack exchange,提问作者bpvcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:40:49