下面在 google chrome 中显示 Pdf 文件的代码不起作用,但在 firefox 中工作。
HTML View
<div>
<object ng-bind="pdfcontent" data="{{pdfcontent}}" type="application/pdf" width="100%" height="800px">
</object>
</div>
Angularjs 代码
$http.get('/myurl/', {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.pdfcontent = $sce.trustAsResourceUrl(fileURL);
});
我收到以下两个错误
firebug-lite.js:18877 Uncaught InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').(anonymous function) @ firebug-lite.js:18877
jquery.js:2812 GET http://abc123.com/%7B%7Bpdfcontent%7D%7D 404 (Not Found)
我的代码有什么问题,如何解决这个问题,不胜感激。 谢谢。
最佳答案
您的问题是,一旦呈现对象,就会绑定(bind) data
属性,因此当您的请求响应时,pdfcontent
不会被绑定(bind)
要解决这个问题,你可以做两个思考
- 为此目的使用指令,如this answer
- 您可以使用
if
语句,如下面的代码片段所示
$scope.downloaded = false
$http.get('/myurl/', {responseType: 'arraybuffer'}).success(function (data) {
$scope.downloaded = true
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.pdfcontent = $sce.trustAsResourceUrl(fileURL);
});
<div ng-if="downloaded">
<object ng-bind="pdfcontent" data="{{pdfcontent}}" type="application/pdf" width="100%" height="800px">
</object>
</div>
关于javascript - 在 google chrome 中显示 Pdf 文件的 Angularjs 代码不起作用,但适用于 Firefox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36983421/