Jithesh kumar
Jithesh kumar

Reputation: 152

Sending pdf file from server to client

I want to send pdf file from server and display it in client side. I'm using server side technology as java and client side as angular 6. Please suggest me. Thanks in advance.

Upvotes: 0

Views: 2432

Answers (1)

Akj
Akj

Reputation: 7231

Using arraybuffer

service call:

In File Service:

getFileFromServer(url){
   return this.httpService.getUploadedFile(url);
}

In HTTP service:

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

in component:

Using Blob

Blob reference -----> Blob

Here this.type = 'application/pdf'

For Example User Clicks on View Button:

than (click)="getPdfFile()" will fire.

It will call service method to get response as 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);
        }

Upvotes: 2

Related Questions