如何在角度服务中通过API获取PDF [英] How to get PDF through API in angular service
问题描述
我在服务器上设置了基于Java的API. URL = "ex.com"
I have a Java based API set up on a server. URL = "ex.com"
它具有一个可返回PDF文件的端点. URL = "ex.com/pdf"
It has an endpoint which returns a PDF file. URL = "ex.com/pdf"
它期望带有参数的POST请求,该参数指定了要请求的PDF. params = { location: "report.pdf"}
It expects a POST request with a parameter specifying which PDF is being requested. params = { location: "report.pdf"}
我希望能够使用可观察到的Angular Http.post来获取PDF,但是它一直抛出HttpErrorResponse Http failure during parsing for http://ex.com/pdf
... Unexpected token % in JSON at position 0 at JSON.parse
.但它是PDF,我不希望将其解析为JSON.
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.
这是我的代码:
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);
}
);
端点与PostMan一起使用.我可以使用发送并下载"选项来成功获取PDF文件.所以我只需要弄清楚如何在Angular中使用它.感谢帮助.
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.
推荐答案
尝试使用这种方法...
Try with something like this...
首先,您将需要 file-saver 节点程序包,因此请运行
npm install --save file-saver
.
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.
让我知道它是否有效!
更新-ANGULAR7& FILESAVER V. ^ 2.0.1 +
我刚刚从Angular v.6和Filesaver v.< 2.0.1迁移了我的应用程序(不知道它是什么版本,但它是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';
到
import { saveAs } from 'file-saver';
其他所有内容都与以前的版本一样!
Everything else works like previous version!
这篇关于如何在角度服务中通过API获取PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!