首页 > 解决方案 > 通过我的 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();
  }

标签: javascriptangularapiexpressnestjs

解决方案


推荐阅读