javascript - 通过我的 NESTJS API 从外部 API 发送 PDF 到 Angular 客户端
问题描述
我正在从 lexoffice API 请求我的 nestjs 后端的发票,它将文件作为二进制值返回。现在我想将它发送给我的角度客户,但我正在努力解决它。最好的方法是它实际上下载了一个文件,打开了一个包含该文档的新选项卡,但它显示了一个错误,即 pdf 无法加载。
我的 API 中的路线:
@Get('invoice/:id')
async downloadInvoice(@Res() res, @Req() req, @Param('id') id: string): Promise<any> {
const resDocFiledId = await this.http.get('https://api.lexoffice.io/v1/invoices/' + id + '/document',
{headers: {Authorization: 'Bearer ' + ServerConstants.lexOfficeApiKey}}).toPromise();
const fileRes = await this.http.get('https://api.lexoffice.io/v1/files/' + resDocFiledId.data.documentFileId,
{
headers: {
Authorization: 'Bearer ' + ServerConstants.lexOfficeApiKey
},
}).toPromise();
res.set({
'Content-Type': 'application/pdf',
'Content-Length': fileRes.headers['content-length'],
});
// fileRes.data is the binary value
res.end(fileRes.data);
}
当我记录它时,fileRes.data 看起来像这样:
JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVhdG9yIChDaHJvbWl1bSkKL1Byb2R1Y2VyIChTa2lhL1BERiBtODYpCi9DcmVhdGlvbkRhdGUgKEQ6MjAyMDExMTAyMzMzNTcrMDAnMDAnKQovTW9kRGF0ZSAoRDoyMDIwMTExMDIzMzM1NyswMCcwMCcpPj4KZW5kb2JqCjMgMCBvYmoKPDwvY2EgMQovQk0gL05vcm1hbD4+CmVuZG9iago2IDAgb2JqCjw8L0ZpbHRlciAvRmxhdGVEZWNvZGUKL0xlbmd0aCAxO ... much longer ofcourse
角度请求:
downloadLexFile(id: string): Observable<any> {
return this.http.get<any>((isDevMode() ? ClientConstants.devServerUrl : ClientConstants.serverUrl) + '/api/shop-data/invoice/' + id, {
headers: {authorization: 'Bearer ' + this.clientAuth.getToken()},
responseType: 'blob',
observe: 'response'
});
}
这就是我在完成后处理请求的方式:
async downloadInvoice(id: string, filename: string): Promise<void> {
const data = (await this.hdap.downloadLexFile(id).toPromise()).body;
const downloadURL = window.URL.createObjectURL(data);
const link = document.createElement('a');
link.target = '_blank';
link.href = downloadURL;
link.download = filename;
link.click();
}
解决方案
推荐阅读
- ios - PhoneGap Build 是否支持 iOS SDK 12.1?
- python - TF 2.0 @tf.function 示例
- python - 正则表达式:删除字符串中间的零(但保留末尾的零)
- c# - 如何在 EF 中为 MSSQL 获取隔离级别?
- php - 使用 laravel 上传 img 进行验证
- c++ - 我该如何解决这个问题,我需要从文本文件中导出一行?
- php - 当不使用`return`语句结束php函数时,它是否被认为是“坏风格”?
- spring-boot - 如何将基于 JDBC URL 的测试容器迁移到 Junit 5
- excel - 循环工作表并创建表格
- java - 为什么 ThreadLocal 不在新线程中创建?