How to get AngularJS BLOB to Download PDF?

后端 未结 5 2072
甜味超标
甜味超标 2021-01-12 08:54

Hello everyone I am really new to developing with AngularJS and I am trying to figure out how to use BLOB to download a PDF locally to a machine. I already got it to work wi

5条回答
  •  无人及你
    2021-01-12 09:35

    Tested with large files (> 1.5 GB) on

    • Firefox 56.0
    • Safari 11.0

    Use the following in your angular controller:

    $scope.download = function() {
     $http({
       method: 'GET',
       url: fileResourceUrl,
       responseType: 'blob'
     }).then(function(response) {
       var blob = response.data;
       startBlobDownload(blob, "largedoc.pdf")
     });
    
    };
    
    function startBlobDownload(dataBlob, suggestedFileName) {
       if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          // for IE
          window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
       } else {
          // for Non-IE (chrome, firefox etc.)
          var urlObject = URL.createObjectURL(dataBlob);
    
          var downloadLink = angular.element('Download');
          downloadLink.css('display','none');
          downloadLink.attr('href', urlObject);
          downloadLink.attr('download', suggestedFileName);
          angular.element(document.body).append(downloadLink);
          downloadLink[0].click();
    
          // cleanup
          downloadLink.remove();
          URL.revokeObjectURL(urlObject);
      }
    }
    

提交回复
热议问题