我正在开发一个Angular 9 web应用程序,在其中一个页面中,客户端期望在提交表单后下载PDF。
我可以在后端(服务器端)成功地生成PDF文件,并使用流返回它。我为返回而开发的Web的输出可以从以下链接中看到:
在我的角度应用程序,我已经尝试了几种方式打开PDF在浏览器或下载作为一个文件。在每一种情况下,我都得到类似于下面的屏幕截图所示的东西。

我第一次尝试的方法是:
loadReport(){
this.spinner.show();
//////// /////////////// /////////////////////
this.api.loadReport(this.filterVM)
.subscribe(res => {
console.log(res);
this.spinner.hide();
////// //////////////////////////
const blob = new Blob([res], { type: 'application/pdf' });
const url= window.URL.createObjectURL(blob);
window.open(url);
////////// /////////////////////
}, err => {
console.log(err);
this.spinner.hide();
});
///// ///////////// //////////////////////////
}第二种方法是:
loadReport(){
this.spinner.show();
//////// /////////////// /////////////////////
this.api.loadReport(this.filterVM)
.subscribe(res => {
console.log(res);
this.spinner.hide();
////// //////////////////////////
this.saveByteArray("Sample Report.pdf", res);
////////// /////////////////////
}, err => {
console.log(err);
this.spinner.hide();
});
///// ///////////// //////////////////////////
}
saveByteArray(reportName, byte) {
var blob = new Blob([byte], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.click();
};第二种方式的输出如下图所示:

当我尝试下载该文件时,我看到它的大小明显小于HTTP响应的大小(9字节和16 KB)。我的Web响应发送以下标题:
Content-Type: application/pdf
Content-Length: 16187
Content-Disposition: attachment; filename=Report.pdf; filename*=UTF-8''Report.pdf我已经尝试过以下博客/网站的代码,但还没有成功。
Download File from Bytes in JavaScript
Typescript blob filename without link
https://blog.liplex.de/download-file-through-typescript/
发布于 2020-09-10 13:25:52
这个问题终于解决了!非常感谢安布罗斯·拉比尔,他在Angular 2 how to display .pdf file上回答了一个类似的问题.他的帖子把我引向了https://medium.com/techinpieces/blobs-with-http-post-and-angular-5-a-short-story-993084811af4 (也谢谢)
更改:
这是我的service.ts文件(在问题中没有共享),https://pastebin.com/vhucnvAX
只更改:我添加了一行
responseType: 'blob' as 'json'在服务类的第一个函数configureOptions()中。我从服务的构造函数中调用这个函数。
我的component.ts文件:https://pastebin.com/d1gB4V8x
https://stackoverflow.com/questions/63828716
复制相似问题