Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileReader onload with result and parameter

Tags:

I can't manage to get both the result of the filereader and some parameters in a onload function. This is my code:

HTML of control:

<input type="file" id="files_input" multiple/> 

Javascript function:

function openFiles(evt){     var files = evt.target.files;     for (var i = 0; i < files.length; i++) {       var file=files[i];       reader = new FileReader();       reader.onload = function(){           var data = $.csv.toArrays(this.result,{separator:'\t'});       };       reader.readAsText(file);     }   } 

Add event:

 files_input.addEventListener("change", openFiles, false); 

I use the filereader.result, in the onload function. If I use a parameter, like file, for this function, I can't not access to the result anymore. For example I'd like to use file.name in the onload function. How to resolve this issue ?

like image 321
PatriceG Avatar asked Dec 02 '14 16:12

PatriceG


People also ask

How can I get FileReader results?

It works by creating a FileReader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read() . The content is handled as raw text data.

What is FileReader onload?

The FileReader. onload property contains an event handler executed when the load event is fired, when content read with readAsArrayBuffer, readAsBinaryString, readAsDataURL or readAsText is available.

Is FileReader onload async?

The FileReader methods work asynchronously but don't return a Promise. And attempting to retrieve the result immediately after calling a method will not work, as the . onload event handler fires only after the FileReader has successfully finished reading the file and updates the FileReader's .

What does FileReader do in Javascript?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.


1 Answers

Try wrapping your onload function in another function. Here the closure gives you access to each file being processed in turn via the variable f:

function openFiles(evt){     var files = evt.target.files;      for (var i = 0, len = files.length; i < len; i++) {         var file = files[i];          var reader = new FileReader();          reader.onload = (function(f) {             return function(e) {                 // Here you can use `e.target.result` or `this.result`                 // and `f.name`.             };         })(file);          reader.readAsText(file);     } } 

For a discussion of why a closure is required here see these related questions:

  • JavaScript closure inside loops – simple practical example
  • Javascript infamous Loop issue?
like image 161
Chris Avatar answered Sep 27 '22 21:09

Chris