java - 将pdf文件从服务器发送到客户端
问题描述
我想从服务器发送 pdf 文件并在客户端显示它。我使用服务器端技术作为 java 和客户端作为 angular 6。请建议我。提前致谢。
解决方案
使用 数组缓冲区
服务电话:
在文件服务中:
getFileFromServer(url){
return this.httpService.getUploadedFile(url);
}
在 HTTP 服务中:
getUploadedFile(url:string){
//just for authentication and file access.
let headers = new HttpHeaders().append("Authorization", "Bearer " + token)
return this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});
}
在组件中:
使用Blob
Blob 参考 -----> Blob
这里 this.type = 'application/pdf'
例如用户点击查看按钮:
不会 (click)="getPdfFile()"
开火。
它将调用服务方法以获取响应arraybuffer
getPdfFile() {
this.fileService.getFileFromServer(url).subscribe(responseData => {
//catch response as array buffer
this.showPdfFile(responseData, this.type);
}, error => {
//catch error if any
console.log(error);
});
}
showPdfFile(data: any, type: string) {
var blob = new Blob([data], { type: type });
var url = window.URL.createObjectURL(blob);
// it will open url to new tab.
window.open(url);
}
推荐阅读
- jmeter - 了解加速期结束期间和之前的用户数量
- wordpress - 如何使用“联系表格 7”在网站中打开数字键盘
- javascript - javaScript 问题 - setItem 正在覆盖 localstorage
- python - 在浏览器中运行时将自写函数导入 Python 文件的问题
- php - php 数组 - 保存价格低于最大值的所有子数组的值
- angular - 使用 monaco 的 Angular 基于 Web 的代码编辑器
- javascript - 检测何时将控件添加到页面 JS/Jquery
- c# - Angular 6 的 C# HttpPost 进度更新
- html - 跨电子邮件客户端 HTML 邮件 v:rect 按钮宽度为 100%
- python - 使用 tf.gfile.GFile 时 Python 退出