AngularJS:$ http.get方法下载pdf文件

时间:2015-10-06 10:45:37

标签: javascript angularjs pdf

  • 我在SPA中使用$ http.get(...)方法获取pdf下载。
  • 在SPA中,print方法给出空白pdf。
  • 但是当我进行调试时,数据来自API。

你可以帮忙吗?

这是将流作为application / pdf

响应的API实现
public Stream GetConsumerInformationReport(Guid id)
 {
   ..........
   var stream = cryRpt.ExportToStream(ExportFormatType.PortableDocFormat);
   return stream;
}

从API获取数据的SPA实现

var print = function () {
            var downloadPath = apiEndPoint + 'Reports/' + $state.current.data.printPrefix + '.pdf';
            $http.get(downloadPath,httpConfig).
                success(function (data) {
                    var blob = new Blob([data], { type: "application/pdf" });
                    var objectUrl = URL.createObjectURL(blob);
                    $window.open(objectUrl);
            }).
            error(function (data, status, headers, config) {
            // if there's an error you should see it here
            });

        };

1 个答案:

答案 0 :(得分:1)

使用此处的http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js

中的FileSaver.js

然后像这样定义你的下载方法。把它当作灵感,不要复制粘贴运行:) 原始版本可在此处找到 - http://davidjs.com/2015/07/download-files-via-post-request-in-angularjs/

    //Define method download() in your ng controller

    $scope.download = () => {
          //Indicates that download is in progress
          $scope.isDownloading = true;

          return $http.get(downloadPath,httpConfig).$promise.then((data: any) => {
                  //using saveAs.js (part of upcoming HTML5 API, but so far a polyfill)
                  var blob = data.response.blob;

                  var fileName: string = data.response.fileName || 'document.pdf';

                  //SaveAs is available at saveAs.js from http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js
                  (<any>$window).saveAs(blob, fileName);
              })
              .finally(() => {
                 $scope.isDownloading = false;
          });
      }