javascript - FileReader onload 仅在浏览器中第二次工作

标签 javascript html angularjs

我正在使用 HTML5 进行浏览器内图像处理,在 Chrome 中遇到一个奇怪的问题,文件 API FileReader 类的 onload 事件处理程序只有在第二次在表单中选择文件时才能正确处理该文件。

知道如何让 Chrome 在第一时间处理这个事件吗? 在我的控制台网络中,当我单击“编辑图像”时,当我第二次单击“编辑”按钮时,什么也没有出现,出现带有图像 blob 的 profilePic。 IDK 发生了什么。

代码:

function uploadFile(){
    var file = $scope.profilePic;
    console.log(file);
    var blob = new Blob([file], {
        "type": "text/html"
    });

    var reader = new FileReader();

    reader.onload = function(e) {
        var text = e.target.result.split(',')[1];
        console.log(text);
        $scope.loadedUser.profilePic = text;
    }

    reader.readAsDataURL(blob);
}; 

html:

<div layout-gt-sm="row" style="margin-bottom: 20px;">                                                    
    <input type="file" name="profilePic" fileread="profilePic"> 
</div>

最佳答案

快速修复是使用$scope.$apply:

reader.onload = function(e) {
    var text = e.target.result.split(',')[1];
    console.log(text);
    $scope.loadedUser.profilePic = text;
    //USE $apply
    $scope.$apply();
}

reader.onload 事件是在 AngularJS 框架之外发生的浏览器事件。对 AngularJS 范围的任何更改都需要使用以 $scope.$apply() 开始的 AngularJS 摘要循环进行处理。


(来源:angularjs.org)

-- AngularJS Developer Guide (v1.1.5) - Concepts - Runtime

关于javascript - FileReader onload 仅在浏览器中第二次工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430901/

相关文章:

javascript - 将 firebase 对象 ID 添加到 Angular 中的 routerlink 属性

Javascript正则表达式重复行匹配无法正常工作

javascript - JSON 响应对象 : "pretty" keys and larger response or short keys and smaller response?

html - 将动画添加到动画中的最终方 block

html - 如何使用 CSS 在 Bootstrap 按钮中添加新行

javascript - 使用 datepicker-options 时如何在 angularjs 中设置最小日期

javascript:创建全局变量的本地范围会在设置之前取消定义它

javascript - 创建水平滚动条的 Google 加号按钮

javascript - 平均堆栈应用: can't hide content using directive "ng-hide' "

javascript - gulp karma 测试 TypeError : Server is not a function