【问题标题】:AngularJS: $http.get method to download the pdf fileAngularJS:$http.get 方法下载 pdf 文件
【发布时间】:2015-10-06 10:45:37
【问题描述】:
  • 我正在使用 SPA 中的 $http.get(...) 方法来获取 pdf 下载。
  • 在 SPA 中,打印方法给出空白 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
            });

        };

【问题讨论】:

  • 您是否尝试在控制台中分别返回成功和错误数据?
  • 在控制台中 - 没有错误,但它进入成功并且数据在那里

标签: javascript angularjs pdf


【解决方案1】:

从这里使用 FileSaver.js http://purl.eligrey.com/github/FileSaver.js/blob/master/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;
          });
      }

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2013-05-31
    • 2014-02-26
    相关资源
    最近更新 更多