Search code examples
javascriptfilereaderractivejs

Get file contents from Ractive on-change event


I'm trying to get the headers of a CSV file I've attached to a file input. I fire a function on change of the file input and check if there are any files in the event and then start a FileReader onload so I can get the contents but the onload function doesn't get fired. Is there something I'm missing?

Ractive.on('getHeaders', function(target) {
  // Check that the file is a file
  if(target.node.files !== undefined) {
    var reader = new FileReader();
    var headers = [];

    reader.onload = function(e) {
      console.log(e);
    };
  }
});

Solution

  • You need to pass the files to the reader, like this:

    Ractive.on('getHeaders', function(target) {
      // Check that the file is a file
      if(target.node.files !== undefined) {
    
        var headers = [];
        target.node.files.forEach(function(file){
    
        var reader = new FileReader();
    
        reader.onload = function(e) {
          console.log(e);
          console.log(reader.result);
        };
    
       reader.readAsDataURL(file);
    
       });      
      }
    });