如何在 AngularJS 应用程序中显示 blob (.pdf) [英] How to Display blob (.pdf) in an AngularJS app
问题描述
我一直在尝试显示从 $http.post
响应中得到的 pdf 文件.例如,pdf 必须使用 显示在应用程序中.
I have been trying to display pdf file which I am getting as a blob from a $http.post
response. The pdf must be displayed within the app using <embed src>
for example.
我遇到了几个堆栈帖子,但不知何故我的示例似乎不起作用.
I came across a couple of stack posts but somehow my example doesn't seem to work.
JS:
根据这个文档,我继续尝试...
According to this doc, I went on and tried...
$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,博客可以将其用作参考.
Now from what I understand, fileURL
creates a temporary URL that the blog can use as a reference.
HTML:
<embed src="{{content}}" width="200" height="200"></embed>
我不确定如何在 Angular 中处理这个问题,理想的情况是 (1) 将它分配给一个范围,(2) '准备/重建' blob 到 pdf (3) 使用 <embed>
将它传递给 HTML,因为我想在应用程序中显示它.
I am not sure how to handle this in Angular, the ideal situation would be to (1) assign it to a scope, (2) 'prepare/rebuild' the blob to a pdf (3) pass it to the HTML using <embed>
because I want to display it within the app.
我已经研究了一天多,但不知何故,我似乎无法理解它在 Angular 中的工作原理......让我们假设 pdf 查看器库没有一个选项.
I have been researching for more than a day now but somehow I can't seem to understand how this works in Angular... And let's just assume the pdf viewer libraries out there weren't an option.
推荐答案
首先需要将 responseType
设置为 arraybuffer
.如果要创建数据 blob,这是必需的.请参阅Sending_and_Receiving_Binary_Data.所以你的代码看起来像这样:
First of all you need to set the responseType
to arraybuffer
. This is required if you want to create a blob of your data. See Sending_and_Receiving_Binary_Data. So your code will look like this:
$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
});
下一部分是,您需要使用 $sce 服务使 Angular 信任您的 url.这可以通过这种方式完成:
The next part is, you need to use the $sce service to make angular trust your url. This can be done in this way:
$scope.content = $sce.trustAsResourceUrl(fileURL);
不要忘记注入 $sce 服务.
Do not forget to inject the $sce service.
如果这一切都完成了,您现在可以嵌入您的 pdf:
If this is all done you can now embed your pdf:
<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
这篇关于如何在 AngularJS 应用程序中显示 blob (.pdf)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!