将pdf文件从服务器发送到客户端

时间:2018-08-25 05:06:43

标签: java angular

我想从服务器发送pdf文件,并在客户端显示它。我正在使用服务器端技术(如Java)和客户端(如Angle 6)。请建议我。预先感谢。

1 个答案:

答案 0 :(得分:2)

使用 arraybuffer

服务电话:

在文件服务中:

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