显示API返回的PDF文档

时间:2018-02-16 15:21:41

标签: javascript angularjs http

我的API返回一个PDF文档,我需要对我的用户进行身份验证。 在我的AngularJS应用程序上,用户单击调用函数的链接:

 <a ng-click="getBankDetails()">Print bank details</a>

控制器:

$scope.getBankDetails = ->
$http.get(ENV.apiEndpoint + "/api/v1/users/get_bank_details", { headers: { 'Accept': 'application/pdf' }, responseType: 'arraybuffer'  })
   .success((resp) ->
     file = new Blob([resp], {type: 'application/pdf'})
     fileURL = URL.createObjectURL(file)
     window.open(file);
   )

但这不起作用。

我已尝试删除API上的身份验证需求。上面的方法仍然不起作用,但如果我这样做

window.open(ENV.apiEndpoint + "/api/v1/users/get_bank_details")

有效。除了确认我的API工作正常之外,没有什么用处。

我使用ng-token-auth进行身份验证

它存储在Cookie中,因为我没有在这里使用cordova

$authProvider.configure
  apiUrl: ENV.apiEndpoint
  storage: if _.isUndefined(window.cordova) then "cookies" else "localStorage"

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

如果您使用基于令牌的身份验证,我会尽可能简单地将authToken添加到URL中以接收文件。通过后端处理authToken作为GET-Param请求:

$scope.getBankDetails = function () {
 window.open(ENV.apiEndpoint + "/api/v1/users/get_bank_details?authToken=XYZ");
}