已解决:如何在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
相关产品推荐
相关产品推荐

