Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

typescript - How to get PDF through API in angular service

I have a Java based API set up on a server. URL = "ex.com"

It has an endpoint which returns a PDF file. URL = "ex.com/pdf"

It expects a POST request with a parameter specifying which PDF is being requested. params = { location: "report.pdf"}

I would like to be able to use the Angular Http.post observable to get the PDF but it keeps throwing an HttpErrorResponse Http failure during parsing for http://ex.com/pdf ... Unexpected token % in JSON at position 0 at JSON.parse. But its a PDF I dont want it to be parsed as JSON.

This is my code:

params = {location: "report.pdf"};
return this.http.post<Response>("http://ex.com/pdf", params)
    .subscribe(
         data => {
            var file = new Blob([data], {type: 'application/pdf'});
            var fileURL = URL.createObjectURL(file);
            window.open(fileURL);
         }
     );

The endpoint works with PostMan. I can use the "Send and Download" option to successfully get the PDF file. So I just need to figure out how to do with in Angular. Appreciate the help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with something like this...

First of all, you will need file-saver node package so run npm install --save file-saver.

Then, try with something like this, I copy-paste my code that I used for something similar

public downloadPDF(): any {
    var mediaType = 'application/pdf';
    this.http.post(this.myUrl, {location: "report.pdf"}, { responseType: 'blob' }).subscribe(
        (response) => {
            var blob = new Blob([response], { type: mediaType });
            saveAs(blob, 'report.pdf');
        },
        e => { throwError(e); }
    );
}

This worked for me, but it was just for saving the file.

Let me know if it works!


UPDATE - ANGULAR7 & FILESAVER V.^2.0.1+


I've just migrated my app from Angular v.6 and Filesaver v.<2.0.1 (don't know what version it was but it was a previous one of 2.0.1).
In this new version, you'll have to change the import from:

import { saveAs } from 'file-saver/FileSaver';

to

import { saveAs } from 'file-saver';

Everything else works like previous version!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...