简体   繁体   English

如何直接从 API (Angular) 下载 pdf?

[英]How can i download the pdf directly from the API (Angular)?

I need to download a PDF from an API in Angular.我需要从Angular中的一个API下载一个PDF。

So, I've written a service to call the API:所以,我写了一个服务来调用 API:

 getPDF(id:any) {
    return this.http.get(
       `url?=${id}`,
        { responseType: 'blob' as 'json', observe: 'response' }
    );
 }

In my component file, I'm calling the service to download the PDF.在我的组件文件中,我正在调用服务来下载 PDF。

  onGeneratepdf() {
    this.service
  .getPDF(
    123
  )
  .subscribe((res: any) => {
    let filename = res.header
    ?.get('content-disposition')
    ?.split(';')[1]
    .split('=')[1];
  let blob: Blob = res.body as Blob;
  var a = document.createElement('a');
  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.click();
  });

} }

after hitting onGeneratePDF, the pdf is downloading but the problem is....it is downloading the file name as undefined.pdf ...it should download as name like user.pdf and also i am getting the response headers as点击 GeneratePDF 后,pdf 正在下载,但问题是......它正在下载文件名undefined.pdf ...它应该以user.pdf之类的名称下载,而且我得到的响应标头为

access-control-allow-origin: *

cache-control: no-cache, no-store, max-age=0, must-revalidate

content-disposition: attachment; filename=user.pdf

content-type: application/pdf

Please help me on these issue.请帮我解决这些问题。

Thanks in advance.提前致谢。

onGeneratepdf() {
        this.service
      .getPDF(
        123
      )
      .subscribe((res: any) => {
        let filename = res.headers
        ?.get('content-disposition')
        ?.split(';')[1]
        .split('=')[1];
      let blob: Blob = res.body as Blob;
      var a = document.createElement('a');
      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.click();
      });

Please try above code, you wrote res.header that should be res.headers请尝试上面的代码,你写的 res.header 应该是 res.headers

if above code not works for you, then take look at below link you will find your solution there Here .如果上面的代码不适合你,那么看看下面的链接,你会在这里找到你的解决方案。

Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM