0

I am trying to allow users to upload a CSV file so that the values can then be displayed and validated. I do not want to upload the file directly to the server, I would like to have it just in scope until it has been validated.

Angular 1.5.8 is unable to bind input types of file to the model see here so I'm looking at using angular-file-upload but all options seem to require uploading to the server. I am unable to find a library that will help me get an input type file into scope.

So my question is: how can I get a csv file into angular scope?

Community
  • 1
  • 1
alichur
  • 925
  • 7
  • 19
  • Did my answer help you? – devnull69 Apr 20 '17 at 11:10
  • Hi, thanks for your answer, sorry I can't give you votes I don't have enough reputation. I used your file reader code inside my directive's link function. `link: (scope, element, attrs) -> uploadFile = (event) -> element.bind('change', uploadFile)` – alichur Apr 20 '17 at 13:05
  • But I think you can accept the answer by clicking on the check mark under the vote count – devnull69 Apr 20 '17 at 13:11

1 Answers1

1

You could use the FileReader for files that have been selected by the user(!)

Your file input:

<input type="file" id="fileInput"/>

Listening for a change event on the element:

document.getElementById("fileInput").addEventListener("change", function(e) {
   var file = e.target.files[0];
   if(!file)
      return;

   var reader = new FileReader();
   reader.onload = function(e) {
      var contents = e.target.result;
      // add it to a $scope variable
      $scope.fileContent = contents;
      $scope.$apply();    // if you are outside of the AngularJS digest cycle
   };
   reader.readAsText(file);       
}, false);
devnull69
  • 16,402
  • 8
  • 50
  • 61