barteloma
barteloma

Reputation: 6855

Getting Angularjs $http post response as file result

I have a very long content request parameters form my web api. So I need send a POST request . And my api is creating a PDF file as response. But I can not get the result with angularjs $http provider.

var req = {
  method: 'POST',
  url: 'http://myapi.com/api/renderfile',
  data: { 
       p1: 'very long text....' ,
       p2: 'another very long text....',
       p3: 'another very long text....' 
  }
}

$scope.isLoading = true;

$http(req).then(function(response){

       // response is file result how can I save it ???

       $scope.isLoading = false;
   }, function(){
       $scope.isLoading = false;
   });

I can not save the file response on client?

response is like this:

enter image description here

When I use FileReader

 new FileReader().readAsDataURL(new Blob([response.data], {type:'application/pdf'}));

The popup appears on browser:

enter image description here

But file is empty.

Upvotes: 5

Views: 11248

Answers (2)

VadimB
VadimB

Reputation: 5711

You can force browser to download this file if you have file content in your response.

var reader = new FileReader();

$http(req).then(function(response){
   reader.readAsDataURL(new Blob([response.data], {type:'application/pdf'}));
});

reader.onload = function(e) { 
    window.open(decodeURIComponent(reader.result), '_self', '', false); 
}

But preferred solution is to include location header in your response with the link to file. So you can force browser to download just by navigating to this link.

Proposed solution works only in HTML5 browsers.

Upvotes: 5

georgeawg
georgeawg

Reputation: 48968

Downloading Binary Files with AngularJS

When downloading binary files it is important to set the responseType attribute of the XHR.

var config = { responseType: 'blob' }

var httpPromise = $http.get(url, config);

httpPromise.then(function (response) {
    $scope.data = response.data;
});

For more information, see MDN XHR API - ResponseType.


Creating a Download Button

This is an example of a Download button that becomes active after the data is loaded from the server:

<a download="data_{{files[0].name}}" xd-href="data">
  <button ng-disabled="!data">Download</button>
</a>

The xdHref Directive

app.module("myApp").directive("xdHref", function() {
  return function linkFn (scope, elem, attrs) {
     scope.$watch(attrs.xdHref, function(newVal) {
       if (newVal) {
         elem.attr("href", newVal);
       }
     });
  };
});

The DEMO on PLNKR.

Upvotes: 2

Related Questions