在角度应用中显示blob(.pdf)

Sim*_*ana 104 pdf blob angularjs

我一直在尝试显示pdf文件,我从$http.post响应中获取blob .例如,pdf必须在应用程序中显示<embed src>.

我遇到了几个堆栈帖子,但不知怎的,我的例子似乎不起作用.

JS:

根据这份文件,我继续尝试......

$http.post('/postUrlHere',{myParams}).success(function (response) {
 var file = new Blob([response], {type: 'application/pdf'});
 var fileURL = URL.createObjectURL(file);
 $scope.content = fileURL;
});
Run Code Online (Sandbox Code Playgroud)

根据我的理解,fileURL创建一个临时URL,博客可以将其用作参考.

HTML:

<embed src="{{content}}" width="200" height="200"></embed>
Run Code Online (Sandbox Code Playgroud)

我不知道如何在Angular中处理这个问题,理想的情况是(1)将它分配给范围,(2) '准备/重建'blob到pdf (3)将其传递给HTML使用<embed>因为我想要在应用程序中显示它.

我已经研究了一天以上但不知何故我似乎无法理解它在Angular中是如何工作的......让我们假设那里的pdf查看器库没有选项.

mic*_*ael 204

首先,你需要设置responseTypearraybuffer.如果要创建数据blob,则必须执行此操作.请参阅Sending_and_Receiving_Binary_Data.所以你的代码看起来像这样:

$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
  .success(function (response) {
       var file = new Blob([response], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
});
Run Code Online (Sandbox Code Playgroud)

接下来的部分是,您需要使用$ sce服务来对您的网址进行角度信任.这可以通过这种方式完成:

$scope.content = $sce.trustAsResourceUrl(fileURL);
Run Code Online (Sandbox Code Playgroud)

别忘了注入$ sce服务.

如果这一切都完成了,你现在可以嵌入你的pdf:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,这在Chrome(35.0.1916.114米)中无效.通过使用<object>而不是<embed>来解决这个问题:<object data ="{{content}}"type ="application/pdf"> </ object> (9认同)
  • 对我来说(AngularJS 1.25)我不得不这样做:新的Blob([response.data] (2认同)
  • @HoffZ:我将快捷方法`$ http.get`替换成一个完整的方法,指定`responseType`字段:```{url:"http://127.0.0.1:8080/resources/jobs/af471106-2e71 -4fe6-946c-cd1809c659e5/result /?key ="+ $ scope.key,method:"GET",headers:{'Accept':'application/pdf'},responseType:'arraybuffer'}```工作:) (2认同)

sgr*_*lon 31

我使用AngularJS v1.3.4

HTML:

<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
Run Code Online (Sandbox Code Playgroud)

JS控制器:

'use strict';
angular.module('xxxxxxxxApp')
    .controller('xxxxController', function ($scope, xxxxServicePDF) {
        $scope.downloadPdf = function () {
            var fileName = "test.pdf";
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";
            xxxxServicePDF.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服务:

angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

Java REST Web服务 - Spring MVC:

@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<byte[]> getPDF() {
        FileInputStream fileStream;
        try {
            fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
            byte[] contents = IOUtils.toByteArray(fileStream);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/pdf"));
            String filename = "test.pdf";
            headers.setContentDispositionFormData(filename, filename);
            ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
            return response;
        } catch (FileNotFoundException e) {
           System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)


Jan*_*män 20

迈克尔的建议对我来说就像一个魅力:)如果用$ http.get替换$ http.post,请记住.get方法接受2个参数而不是3个...这就是浪费我的时间......;)

控制器:

$http.get('/getdoc/' + $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)

视图:

<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>
Run Code Online (Sandbox Code Playgroud)


Man*_*dez 9

我在Opera浏览器中使用"window.URL"时遇到了困难,因为它会导致"未定义".此外,使用window.URL,PDF文档永远不会在Internet Explorer和Microsoft Edge中打开(它将永远等待).我提出了以下解决方案,适用于IE,Edge,Firefox,Chrome和Opera(未经Safari测试):

$http.post(postUrl, data, {responseType: 'arraybuffer'})
.success(success).error(failed);

function success(data) {
   openPDF(data.data, "myPDFdoc.pdf");
};

function failed(error) {...};

function openPDF(resData, fileName) {
    var ieEDGE = navigator.userAgent.match(/Edge/g);
    var ie = navigator.userAgent.match(/.NET/g); // IE 11+
    var oldIE = navigator.userAgent.match(/MSIE/g); 

    var blob = new window.Blob([resData], { type: 'application/pdf' });

    if (ie || oldIE || ieEDGE) {
       window.navigator.msSaveBlob(blob, fileName);
    }
    else {
       var reader = new window.FileReader();
       reader.onloadend = function () {
          window.location.href = reader.result;
       };
       reader.readAsDataURL(blob);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有帮助,请告诉我!:)


小智 6

responseType添加到由angular生成的请求确实是解决方案,但对我来说,直到我将responseType设置为blob而不是arrayBuffer才能生效.代码是自我解释的:

    $http({
            method : 'GET',
            url : 'api/paperAttachments/download/' + id,
            responseType: "blob"
        }).then(function successCallback(response) {
            console.log(response);
             var blob = new Blob([response.data]);
             FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
        }, function errorCallback(response) {   
        });
Run Code Online (Sandbox Code Playgroud)

  • 实际上,使用`'blob'`类型可以编写更短的内容:`FileSaver.saveAs(response.data,getFileNameFromHttpResponse(response));`无需创建`Blob` (2认同)

归档时间:

查看次数:

225870 次

最近记录:

6 年,11 月 前