0

我在这个问题一天。当我尝试点击更新图像按钮时,会发生以下情况:尽管使用console.log,我仍然无法在第一次尝试中进行图像更新,但它会将正确的值返回给我。会发生什么是当我第一次加载更新按钮时向后端发出请求时,它总是返回先前图像的blob,当我再次尝试时,它会返回我尝试在图像中执行的图像的blob先前的时刻并插入到数据库中。总之,他总是提出迟到的要求,我并没有这么做,因为。我已经尝试添加$ scope。 $ Apply()并没有工作。Reader.onload上传图像文件到blob angularjs

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; 
       }); 
      }); 
     } 
    } 
}]); 

回答

0

部分原因是DIRECTI ve使用与隔离范围绑定的双向=。摘要周期对于将数据从隔离范围转移到父范围是必要的。

一种方法是使用表达&结合和暴露所述文件作为本地:

<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属性与文件公开为$file$file值可立即用于父范围,而无需观察者(和摘要循环)将值从隔离范围转移到父范围。

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