首页 > 解决方案 > 将pdf文件从服务器发送到客户端

问题描述

我想从服务器发送 pdf 文件并在客户端显示它。我使用服务器端技术作为 java 和客户端作为 angular 6。请建议我。提前致谢。

标签: javaangular

解决方案


使用 数组缓冲区

服务电话:

在文件服务中:

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);
        }

推荐阅读