javascript - 在 google chrome 中显示 Pdf 文件的 Angularjs 代码不起作用,但适用于 Firefox

标签 javascript angularjs google-chrome firefox pdf

下面在 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)

要解决这个问题,你可以做两个思考

  1. 为此目的使用指令,如this answer
  2. 您可以使用 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/

相关文章:

java - 当我从 struts2 操作的 js 函数中获取 JSONArray 时,它是空的,我不明白为什么

angularjs - 在 AngularJS 应用程序中运行 Karma 单元测试时出现 "Unexpected request"错误

javascript - 我的 Javascript 代码在 chrome 中不起作用

.net - IIS localhost 上不允许的 405 方法从昨天开始不起作用

javascript - 这个脚本标签在 Firefox 中工作正常,但在 Chrome 中不行(因为遇到一些安全问题)

javascript - $.getJSON 很慢

javascript - 更改 anchor 处的滚动方向

javascript - 不向从 javascript Date 创建的对象添加分钟的时刻

angularjs - 在 CORS 中真的需要 Angular $http.defaults.useR 域吗?

javascript - 如何强制水平滚动在 UI-GRID 上向右移动