在Angular 7中,通过HttpClient发送GET请求获取PDF文件时,可以将其解析为Blob对象。以下是一个示例解决方法:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
getPdf(): void {
this.http.get('URL_TO_PDF', { responseType: 'blob' })
.subscribe((response: Blob) => {
this.saveFile(response, 'file.pdf');
}, error => {
console.error(error);
});
}
saveFile(response: Blob, fileName: string): void {
const a: HTMLAnchorElement = document.createElement('a');
document.body.appendChild(a);
const file = new Blob([response], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(fileURL);
}
在上述代码中,URL_TO_PDF
是你要请求的PDF文件的URL。responseType: 'blob'
将告诉HttpClient将响应解析为Blob对象。
saveFile
方法将Blob对象创建为URL,并将其链接添加到一个隐藏的链接元素中。然后,通过调用a.click()
模拟用户点击该链接来下载文件。
getPdf
方法:this.getPdf();
这样,Angular应用就能够正确地从服务器获取PDF文件并将其解析为Blob对象。