如何让AngularJS BLOB下载PDF?

use*_*107 6 angularjs

大家好,我是开发AngularJS的新手,我正在试图弄清楚如何使用BLOB将PDF本地下载到一台机器上.我已经让它使用JSON,现在我需要一个PDF.我写了一些代码,但似乎没有用.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .center {
            position: absolute;
            left: 50%;
            bottom: 50%;
        }

        .btn-purple {
            background-color: rgb(97, 34, 115);
            width: 100px;
        }

    </style>
    <meta charset="UTF-8">
    <title></title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
          integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>


<body>
<div class="center" ng-controller="jsonController" ng-app="app">
    <a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
        <button type="button" class="btn btn-purple">{{fileName}}</button>
    </a>
</div>

<div class="center" ng-controller="pdfController" ng-app="app">
    <a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
        <button type="button" class="btn btn-purple">{{fileName}}</button>
    </a>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.1.0/js/canvas-to-blob.js"></script>
<script src="app.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

controller.js

var app = angular.module('app', []);

app.config(['$compileProvider', function ($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);

app.controller('jsonController', function ($scope, $window, $http, $log) {
    $http.get('data.json')
        .success(function (info) {
            var data = angular.toJson(info, true);
            data = data.replace(/\n/g, "\r\n")
            console.log(data)
            var blob = new Blob([data], {type: "octet/stream"}),
                url = $window.URL || $window.webkitURL;
            $scope.fileUrl = url.createObjectURL(blob);
            $scope.schemaName = "test"
            $scope.fileName = $scope.schemaName + ".json"
        })
});
app.controller("pdfController", function ($scope, $http, $log, $sce) {
    $http.get('data.json' + $stateParams.id,
        {responseType: 'arraybuffer'})
        .success(function (response) {
            var file = new Blob([(response)], {type: 'application/pdf'});
            var fileURL = URL.createObjectURL(file);
            $scope.content = $sce.trustAsResourceUrl(fileURL);
        });
});
Run Code Online (Sandbox Code Playgroud)

Zee*_*mon 16

可能尝试 -

HTML:

<button ng-click="downloadPdf()" >Download PDF</button>
Run Code Online (Sandbox Code Playgroud)

JS控制器:

'use strict';
var app = angular.module('app')
    .controller('ctrl', function ($scope, MathServicePDF) {
        $scope.downloadPdf = function () {
            var fileName = "file_name.pdf";
            var a = document.createElement("a");
            document.body.appendChild(a);
            ServicePDF.downloadPdf().then(function (result) {
                var file = new Blob([result.data], {type: 'application/pdf'});
                var fileURL = window.URL.createObjectURL(file);
                a.href = fileURL;
                a.download = fileName;
                a.click();
            });
        };
});
Run Code Online (Sandbox Code Playgroud)

JS服务:

app.factory('ServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/my-pdf', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

快乐帮助!


Ste*_* Oh 7

已通过测试大型文件(> 1.5 GB

  • Firefox 56.0
  • 的Safari 11.0

在角度控制器中使用以下命令:

$scope.download = function() {
 $http({
   method: 'GET',
   url: fileResourceUrl,
   responseType: 'blob'
 }).then(function(response) {
   var blob = response.data;
   startBlobDownload(blob, "largedoc.pdf")
 });

};

function startBlobDownload(dataBlob, suggestedFileName) {
   if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      // for IE
      window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
   } else {
      // for Non-IE (chrome, firefox etc.)
      var urlObject = URL.createObjectURL(dataBlob);

      var downloadLink = angular.element('<a>Download</a>');
      downloadLink.css('display','none');
      downloadLink.attr('href', urlObject);
      downloadLink.attr('download', suggestedFileName);
      angular.element(document.body).append(downloadLink);
      downloadLink[0].click();

      // cleanup
      downloadLink.remove();
      URL.revokeObjectURL(urlObject);
  }
}
Run Code Online (Sandbox Code Playgroud)