【发布时间】:2017-12-03 03:08:41
【问题描述】:
在我的 Angular 应用程序中,我需要在单击按钮时打开 PDF。
我首先按照this帖子给出的指示,所以我现在有这两种方法:
在调用组件中
public PrepareDownload(){
this._certificateService
.GetPdf(args)
.subscribe(
result => {
this.BlobUri = URL.createObjectURL(result);
}
}
public Download() {
window.open(this.BlobUri);
}
服务中
public GetPdf() : any {
var headers = new Headers();
headers.append("Content-Type", "application/json");
var payload = {id:215};
return this._http.post(this.requestUri,
JSON.stringify(payload),
{ headers: headers,
responseType: ResponseContentType.Blob })
.map((response: Response) =>
{
return new Blob([response.blob()], { type: 'application/pdf' });
});
}
GetPdf 的响应包含一个类似于以下[ 37,80,68,70,45,49,46,...] 的数组。不幸的是,当调用下载方法时,结果似乎是一个无效的pdf。通过firefox下载文件并将其重命名为txt文件时,我可以看到内容不是二进制而是完整的字节数组作为字符串。
【问题讨论】:
-
我认为没有必要重新包装 blob,
(response: Response) => response.blob()通常对我有用。 -
当不添加类型标题时,浏览器甚至不会尝试使用 pdf 查看器打开它。要添加这些标题,我重新包装。
-
好吧,首先确保服务器返回正确的 Content-Type。
-
这是一个很好的提示。我调整了我的服务器代码以返回一个流而不是一个字节数组。像魅力一样工作。