获取Angularjs $ http post response作为文件结果

时间:2017-02-28 13:14:15

标签: angularjs

我的web api中有一个很长的内容请求参数。所以我需要发送一个POST请求。我的api正在创建一个PDF文件作为回应。但我无法通过angularjs $ http提供商获得结果。

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

我无法在客户端保存文件响应?

响应是这样的:

enter image description here

当我使用FileReader

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

弹出窗口显示在浏览器上:

enter image description here

但文件是空的。

2 个答案:

答案 0 :(得分:4)

如果您的回复中包含文件内容,则可以强制浏览器下载此文件。

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

但首选解决方案是在您的回复中包含location标头以及指向文件的链接。因此,您只需导航到此链接即可强制浏览器下载。

建议的解决方案仅适用于HTML5浏览器。

答案 1 :(得分:1)

使用AngularJS下载二进制文件

下载二进制文件时,设置XHR的responseType属性非常重要。

var config = { responseType: 'blob' }

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

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

有关详细信息,请参阅MDN XHR API - ResponseType.

创建下载按钮

这是一个 Download 按钮的示例,该按钮在从服务器加载数据后变为活动

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

xdHref 指令

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

DEMO on PLNKR.