How to Display blob (.pdf) in an AngularJS app

后端 未结 8 1433
逝去的感伤
逝去的感伤 2020-11-22 11:01

I have been trying to display pdf file which I am getting as a blob from a $http.post response. The pdf must be displayed within the app using

8条回答
  •  清歌不尽
    2020-11-22 11:40

    I have struggled for the past couple of days trying to download pdfs and images,all I was able to download was simple text files.

    Most of the questions have the same components, but it took a while to figure out the right order to make it work.

    Thank you @Nikolay Melnikov, your comment/reply to this question was what made it work.

    In a nutshell, here is my AngularJS Service backend call:

      getDownloadUrl(fileID){
        //
        //Get the download url of the file
        let fullPath = this.paths.downloadServerURL + fileId;
        //
        // return the file as arraybuffer 
        return this.$http.get(fullPath, {
          headers: {
            'Authorization': 'Bearer ' + this.sessionService.getToken()
          },
          responseType: 'arraybuffer'
        });
      }
    

    From my controller:

    downloadFile(){
       myService.getDownloadUrl(idOfTheFile).then( (response) => {
          //Create a new blob object
          let myBlobObject=new Blob([response.data],{ type:'application/pdf'});
    
          //Ideally the mime type can change based on the file extension
          //let myBlobObject=new Blob([response.data],{ type: mimeType});
    
          var url = window.URL || window.webkitURL
          var fileURL = url.createObjectURL(myBlobObject);
          var downloadLink = angular.element('');
          downloadLink.attr('href',fileURL);
          downloadLink.attr('download',this.myFilesObj[documentId].name);
          downloadLink.attr('target','_self');
          downloadLink[0].click();//call click function
          url.revokeObjectURL(fileURL);//revoke the object from URL
        });
    }
    

提交回复
热议问题