【问题标题】:Reader.onload upload image file to blob angularjsReader.onload 将图像文件上传到 blob angularjs
【发布时间】:2017-01-04 02:48:36
【问题描述】:

我每天都遇到这个问题。当我尝试单击更新图像按钮时会发生以下情况,尽管我的 console.log 它返回了正确的值,但我在第一次尝试时无法进行图像更新。发生的情况是,当我第一次加载更新按钮时向后端发出请求时,它总是返回先前图像的 blob,当我再次尝试时,它返回我尝试在前一刻并插入数据库。简而言之,他总是提出迟到的要求,而我一点也不做,因为。我已经尝试添加 $ 范围。 $apply() 没用。

First update the blob of the previous image

Second update the blob correct of the image

简而言之,我需要更新两次才能将图像更改为我想要的图像。

代码:

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

    var reader = new FileReader();

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

    reader.readAsDataURL(blob);

}; 

HTML:

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

APP:

app.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                scope.$apply(function () {
                    scope.fileread = changeEvent.target.files[0];
                    // or all selected files:
                    // scope.fileread = changeEvent.target.files;
                });
            }); 
        } 
    }
}]);

【问题讨论】:

    标签: javascript angularjs image angularjs-directive angularjs-scope


    【解决方案1】:

    部分问题是该指令使用双向= 绑定与隔离范围。将数据从隔离作用域传输到父作用域需要一个摘要循环。

    一种方法是使用表达式&amp; 绑定并将文件公开为本地:

    <div layout-gt-sm="row" style="margin-bottom: 20px;">
        <input type="file" name="profilePic" fileread="profilePic = $file">
    </div>
    
    app.directive("fileread", function () {
        return {
            scope: {
                //fileread: "="
                fileread: "&"
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    scope.$apply(function () {
                    var file = changeEvent.target.files[0];
                    scope.fileread({$file: file});
                    scope.$apply()
                }); 
            } 
        }
    });
    

    在上面的示例中,当发生更改事件时,该指令评估由fileread 属性定义的Angular 表达式,文件公开为$file$file 值立即可供父范围使用,无需观察者(和摘要循环)将值从隔离范围传输到父范围。

    另一个问题是reader.onload 事件发生在AngularJS 框架之外,需要$scope.$apply() 来处理对范围的更改。如需更多信息,请参阅SO: FileReader onload only works the second time around in browsers

    【讨论】:

      猜你喜欢
      • 2017-07-12
      • 2020-06-12
      • 2013-07-29
      • 2017-04-26
      • 1970-01-01
      • 2015-04-23
      • 2018-12-17
      • 2018-06-14
      • 2015-05-15
      相关资源
      最近更新 更多