FileReader does not upload file using AngularJS

I am trying to upload a csv file to AngularJS, so I can do some manipulation of the content. This is not quite the way I want. To verify that the download is correct, I upload it to a text box to view the contents.

When I upload the file, it says that it loaded correctly, but the onload () event does not seem to fire until I load the second CSV file, in which case the FIRST file is displayed in the text box.

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

And when I put this in a JSFiddle, the file does not appear at all in the text box. I am new to JSFiddle, so I don't know why this is happening.

Any help at all would be appreciated.

+5
source share
2 answers

Reordering some lines of your code, I hope that the comments are quite sensible

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

Link: FileReader on MDN

+13
source

This is a slight HTML improvement:

 <input type="file" onchange="angular.element(this).scope().file_changed(this)"/> <textarea cols="75" rows="15">{{ dataFile }}</textarea> 

and controller:

 .controller('MyCtrl', ['$scope', function($scope) { var vm = $scope; vm.file_changed = function(element){ var dataFile = element.files[0]; var reader = new FileReader(); reader.onload = function(e){ vm.$apply(function(){ vm.dataFile = reader.result; }); }; reader.readAsText(dataFile); }; }]); 

Link

+1
source

Source: https://habr.com/ru/post/1203884/


All Articles