FileReader onload仅在浏览器中第二次运行 [英] FileReader onload only works the second time around in browsers
问题描述
我正在使用HTML5处理浏览器内图像处理,并且在Chrome中使用onload事件处理程序处理File API FileReader类时出现了一个奇怪问题,该文件仅在第二次在表单中选择时才正确处理。 p>
任何想法我怎么能让Chrome第一次处理这个事件?
在我的控制台网络中,当我点击编辑图像时,不会出现任何东西,当我点击编辑按钮中的第二个按钮时,会出现带有图像blob的profilePic。
IDK发生了什么事情。
代码:
函数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(文本);
$ scope.loadedUser.profilePic = text;
}
reader.readAsDataURL(blob);
};
html:
< div layout-gt-sm =rowstyle =margin-bottom:20px;>
< input type =filename =profilePicfileread =profilePic>
< / div>
快速修复是使用 $ scope。$ apply
:
reader.onload = function(e){
var text = e.target.result.split(',')[1];
console.log(文本);
$ scope.loadedUser.profilePic = text;
// USE $ apply
$ scope。$ apply();
reader.onload
事件是在AngularJS框架之外发生的浏览器事件。对AngularJS范围的任何更改都需要使用以 $ scope开头的AngularJS摘要循环进行处理。$ apply()
。
- AngularJS开发人员指南(v1.1.5) - 概念 - 运行时间
I'm working on in-browser image processing with HTML5 and have a weird issue in Chrome with the onload event handler for the File API FileReader class the file is only processed properly the second time it's selected in the form.
Any idea how I can get Chrome to process this event the first time around? In my console network when i click edit image don't appear nothing when i click the second time in edit button appear me the profilePic with the image blob. IDK what happen.
Code:
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>
The quick fix is to use $scope.$apply
:
reader.onload = function(e) {
var text = e.target.result.split(',')[1];
console.log(text);
$scope.loadedUser.profilePic = text;
//USE $apply
$scope.$apply();
}
The reader.onload
event is a browser event which occurs outside the AngularJS framework. Any changes to the AngularJS scope need to be processed with an AngularJS digest cycle which is started with $scope.$apply()
.
-- AngularJS Developer Guide (v1.1.5) - Concepts - Runtime
这篇关于FileReader onload仅在浏览器中第二次运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!