Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在AngularJS应用程序中显示blob(.pdf)_Angularjs_Pdf_Blob - Fatal编程技术网

如何在AngularJS应用程序中显示blob(.pdf)

如何在AngularJS应用程序中显示blob(.pdf),angularjs,pdf,blob,Angularjs,Pdf,Blob,我一直在尝试显示pdf文件,我从$http.post响应中得到一个blob。pdf必须在应用程序中显示,例如使用 我遇到了几个堆栈帖子,但不知何故,我的示例似乎不起作用 JS: <embed src="{{content}}" width="200" height="200"></embed> <button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>

我一直在尝试显示pdf文件,我从
$http.post
响应中得到一个blob。pdf必须在应用程序中显示,例如使用

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

JS:

<embed src="{{content}}" width="200" height="200"></embed>
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
'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();
            });
        };
});
angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});
@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;
    }
据我所知,我继续努力

$http.post('/postUrlHere',{myParams}).success(function (response) {
 var file = new Blob([response], {type: 'application/pdf'});
 var fileURL = URL.createObjectURL(file);
 $scope.content = fileURL;
});
现在据我所知,
fileURL
创建了一个临时URL,博客可以将其用作参考

HTML:

<embed src="{{content}}" width="200" height="200"></embed>
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
'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();
            });
        };
});
angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});
@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;
    }

我不知道如何处理这个问题,理想的情况是(1)将其分配给一个作用域,(2)“准备/重建”blob到pdf(3)使用
将其传递到HTML,因为我想在应用程序中显示它


我已经研究了一天多了,但不知何故,我似乎不明白这是如何在角度。。。让我们假设pdf查看器库没有选项。

首先,您需要将
响应类型设置为
arraybuffer
。如果要创建数据的blob,则需要此选项。看见因此,您的代码将如下所示:

$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
  .success(function (response) {
       var file = new Blob([response], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
});
下一部分是,您需要使用该服务来创建url。这可以通过以下方式完成:

$scope.content = $sce.trustAsResourceUrl(fileURL);
不要忘记注入服务

如果全部完成,您现在可以嵌入您的pdf:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>

我使用AngularJS v1.3.4

HTML:

<embed src="{{content}}" width="200" height="200"></embed>
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
'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();
            });
        };
});
angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});
@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;
    }
JS服务:

<embed src="{{content}}" width="200" height="200"></embed>
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
'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();
            });
        };
});
angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});
@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;
    }
JavaRESTWeb服务-SpringMVC:

<embed src="{{content}}" width="200" height="200"></embed>
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
'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();
            });
        };
});
angular.module('xxxxxxxxApp')
    .factory('xxxxServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});
@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;
    }
@RequestMapping(value=“/downloadPDF”,method=RequestMethod.GET,products=“application/pdf”)
公共响应getPDF(){
FileInputStream文件流;
试一试{
fileStream=newfileinputstream(新文件(“C:\\xxxxx\\xxxxxx\\test.pdf”);
byte[]contents=IOUtils.toByteArray(fileStream);
HttpHeaders=新的HttpHeaders();
headers.setContentType(MediaType.parseMediaType(“application/pdf”);
字符串filename=“test.pdf”;
headers.setContentDispositionFormData(文件名、文件名);
ResponseEntity response=新的ResponseEntity(内容、标题、HttpStatus.OK);
返回响应;
}catch(filenotfounde异常){
系统错误println(e);
}捕获(IOE异常){
系统错误println(e);
}
返回null;
}

迈克尔的建议对我很有吸引力:) 如果将$http.post替换为$http.get,请记住.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);
});
downloadFile(){
   myService.getDownloadUrl(idOfTheFile).then( (response) => {
      //Create a new blob object
      let myBlobObject=new Blob([response.data],{ type:'application/pdf'});

      //Ideally the mime type can change based on the file extension
      //let myBlobObject=new Blob([response.data],{ type: mimeType});

      var url = window.URL || window.webkitURL
      var fileURL = url.createObjectURL(myBlobObject);
      var downloadLink = angular.element('<a></a>');
      downloadLink.attr('href',fileURL);
      downloadLink.attr('download',this.myFilesObj[documentId].name);
      downloadLink.attr('target','_self');
      downloadLink[0].click();//call click function
      url.revokeObjectURL(fileURL);//revoke the object from URL
    });
}
视图:


我在Opera浏览器中使用“window.URL”时遇到困难,因为这会导致“未定义”。此外,对于window.URL,PDF文档从未在Internet Explorer和Microsoft Edge中打开过(它将永远等待)。我提出了以下在IE、Edge、Firefox、Chrome和Opera中使用的解决方案(尚未使用Safari进行测试):


让我知道它是否有用!:)

过去几天我一直在努力下载PDF和图像,我只能下载简单的文本文件

大多数问题都有相同的组成部分,但需要一段时间才能找出正确的顺序,使其正常工作

谢谢@Nikolay Melnikov,你对这个问题的评论/回答是什么让它起作用的

简而言之,以下是我的AngularJS服务后端调用:

  getDownloadUrl(fileID){
    //
    //Get the download url of the file
    let fullPath = this.paths.downloadServerURL + fileId;
    //
    // return the file as arraybuffer 
    return this.$http.get(fullPath, {
      headers: {
        'Authorization': 'Bearer ' + this.sessionService.getToken()
      },
      responseType: 'arraybuffer'
    });
  }
从我的控制器:

$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);
});
downloadFile(){
   myService.getDownloadUrl(idOfTheFile).then( (response) => {
      //Create a new blob object
      let myBlobObject=new Blob([response.data],{ type:'application/pdf'});

      //Ideally the mime type can change based on the file extension
      //let myBlobObject=new Blob([response.data],{ type: mimeType});

      var url = window.URL || window.webkitURL
      var fileURL = url.createObjectURL(myBlobObject);
      var downloadLink = angular.element('<a></a>');
      downloadLink.attr('href',fileURL);
      downloadLink.attr('download',this.myFilesObj[documentId].name);
      downloadLink.attr('target','_self');
      downloadLink[0].click();//call click function
      url.revokeObjectURL(fileURL);//revoke the object from URL
    });
}
下载文件(){
myService.getDownloadUrl(idOfTheFile).then((响应)=>{
//创建新的blob对象
让myBlobObject=newBlob([response.data],{type:'application/pdf});
//理想情况下,mime类型可以根据文件扩展名进行更改
//让myBlobObject=newBlob([response.data],{type:mimeType});
var url=window.url | | window.webkitURL
var fileURL=url.createObjectURL(myBlobObject);
var downloadLink=angular.element(“”);
downloadLink.attr('href',fileURL);
downloadLink.attr('download',this.myFilesObj[documentId].name);
downloadLink.attr('target','u self');
下载链接[0]。单击();//调用单击函数
revokeObjectURL(fileURL);//从url中撤销对象
});
}

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) {   
        });

我刚刚在使用AngularJSV1.7.2的项目中使用的代码建议

$http.get('LabelsPDF?ids=' + ids, { responseType: 'arraybuffer' })
            .then(function (response) {
                var file = new Blob([response.data], { type: 'application/pdf' });
                var fileURL = URL.createObjectURL(file);
                $scope.ContentPDF = $sce.trustAsResourceUrl(fileURL);
            });

<embed ng-src="{{ContentPDF}}" type="application/pdf" class="col-xs-12" style="height:100px; text-align:center;" />
$http.get('LabelsPDF?ids='+ids,{responseType:'arraybuffer'})
.然后(功能(响应){
var file=newblob([response.data],{type:'application/pdf'});
var fileURL=URL.createObjectURL(文件);
$scope.ContentPDF=$sce.trustAsResourceUrl(fileURL);
});
最近的答案(对于8+):

this.http.post(“您的url”,参数,{responseType:'arraybuffer'作为'json'})。订阅(
(res)=>{
本文件为PDF(res);
}
)};
公共内容:安全资源URL;
showpdf(回复:ArrayBuffer){
var file=newblob([response],{type:'application/pdf'});
var fileURL=URL.createObjectURL(文件);
this.Content=this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}
HTML:

对我来说,这在Chrome(35.0.1916.114米)中不起作用。通过使用而不是:For me(AngularJS 1.25)解决了这个问题,我必须执行:new Blob([response.data]@HoffZ:I用一个完整的方法替换快捷方式
$http.get
,指定
responseType
字段:
{url:http://127.0.0.1:8080/resources/jobs/af471106-2e71-4fe6-946c-cd1809c659e5/结果/?键=”+$scope.key,方法:“GET”,标题:{'Accept':'application/pdf'},