使用AngularJS的FileReader不加载文件正确 [英] FileReader not loading file properly using AngularJS
问题描述
我想一个CSV文件加载到AngularJS所以我可以做的内容有一些操作。这是不太工作,我希望它。为了测试是否正确加载,我加载到一个textarea查看其内容。
I'm trying to load a csv file into AngularJS so I can do some manipulation on the contents. It is not quite working as I want it to. To test if it is loading properly, I am loading it into a textarea to view the contents.
当我加载文件时,它说,这是正确加载,但在onload()事件似乎并没有被解雇,直到我打开第二个CSV文件,在这种情况下,第一个文件显示在文本区域。
When I load the file, it says it is loaded properly but the onload() event doesn't seem to be firing until I load a second CSV file, in which case the FIRST file is displayed in the textarea.
HTML
<div>
<input ng-model="csv"
onchange="angular.element(this).scope().fileChanged()"
type="file" accept=".csv" id="fileInput"/>
</div>
<br/>
<div>
<textarea ng-model="csvFile" readonly="true" style="width:99%; height:500px" disabled></textarea>
</div>
JS:
$scope.fileChanged = function() {
$scope.$apply(function() {
var csvFileInput = document.getElementById('fileInput');
var reader = new FileReader();
var csvFile = csvFileInput.files[0];
reader.onload = function(e) {
$scope.csvFile = reader.result;
};
reader.readAsText(csvFile);
});
};
而当我把这个进入的jsfiddle,该文件不会出现在textarea的都没有。我是新用的jsfiddle,所以我不知道为什么会发生根本。
And when I put this into JSFiddle, the file doesn't appear in the textarea at all. I'm new with JSFiddle so I don't know why that is happening.
任何帮助都将是AP preciated。
Any help at all would be appreciated.
推荐答案
重新排列你的code的一些线路,希望意见足以说明
Reordering some lines of your code, hope the comments are explanatory enough
$scope.fileChanged = function() {
// define reader
var reader = new FileReader();
// A handler for the load event (just defining it, not executing it right now)
reader.onload = function(e) {
$scope.$apply(function() {
$scope.csvFile = reader.result;
});
};
// get <input> element and the selected file
var csvFileInput = document.getElementById('fileInput');
var csvFile = csvFileInput.files[0];
// use reader to read the selected file
// when read operation is successfully finished the load event is triggered
// and handled by our reader.onload function
reader.readAsText(csvFile);
};
这篇关于使用AngularJS的FileReader不加载文件正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!