我一直在尝试显示pdf文件,我将其作为$http.post
响应中的blob获取。例如,必须使用<embed src>
在应用程序中显示pdf。
我遇到了几个堆叠帖子,但不知怎的,我的例子似乎不起作用。
JS:
根据this doc,我继续尝试......
$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>
我不知道如何在Angular中处理这个问题,理想的情况是(1)将其分配到范围,(2)'prepare / rebuild 'blob到pdf (3)使用<embed>
将其传递给HTML,因为我想在应用中显示它。
我现在已经研究了一天多,但不知怎的,我似乎无法理解它在Angular中是如何工作的...让我们假设那里的pdf查看器库没有选项。
答案 0 :(得分:198)
首先,您需要将responseType
设置为arraybuffer
。如果要创建数据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);
});
接下来的部分是,您需要使用$sce服务来对您的网址进行角度信任。这可以通过这种方式完成:
$scope.content = $sce.trustAsResourceUrl(fileURL);
不要忘记注入$sce服务。
如果这一切都完成了,你现在可以嵌入你的pdf:
<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
答案 1 :(得分:31)
我使用AngularJS v1.3.4
<强> HTML:强>
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
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();
});
};
});
JS服务:
angular.module('xxxxxxxxApp')
.factory('xxxxServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
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;
}
答案 2 :(得分: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);
});
视图:
<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>
答案 3 :(得分:10)
我在使用&#34; window.URL&#34;时遇到了困难。使用Opera浏览器,因为它会导致&#34;未定义&#34;。此外,使用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);
}
}
让我知道它是否有帮助! :)
答案 4 :(得分:6)
将 responseType 添加到由角度构成的请求确实是解决方案,但对我来说,在我设置 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) {
});
答案 5 :(得分:0)
过去几天我一直在努力下载pdfs和图片,我能够下载的只是简单的文本文件。
大多数问题都有相同的组件,但需要一段时间来确定正确的顺序才能使其正常工作。
谢谢@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'
});
}
来自我的控制器:
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
});
}
答案 6 :(得分:0)
最新答案(针对Angular 8 +):
this.http.post("your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
(res) => {
this.showpdf(res);
}
)};
public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}
HTML :
<embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />
答案 7 :(得分:-1)
我刚刚在使用AngularJS v1.7.2的项目中使用的代码建议
from pairs