Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename after filereader asynchronously loaded a file

I am loading several files in a directory in order to parse some data from them. This works great so far, but I would like to know which file I am looking at. So I need the name of the file after it was loaded. Can anybody help on that?

// gets all files in dir

function updateData(){   var dirReader = approot.createReader();    var fail =failCB('Error - Directory for parsing failed to open'); // logs fail...   dirReader.readEntries(parseData,fail);  } 

// loading each file

function parseData(entries){   var i;   for (i=0; i<entries.length; i++) {     var reader = new FileReader();     reader.onloadend = createListItem;     reader.readAsText(entries[i]);   } } 

// HERE I WOULD LIKE TO KNOW THE NAME !!!!

function createListItem(evt){     // it gives me all the loaded data. But based on which file it was, I would like to handle it!   console.log(evt.target.result)     // lets say something like this     $('#content').find(   file.name   ).append(evt.target.result);   } } 
like image 285
Sidrich2009 Avatar asked Sep 22 '12 18:09

Sidrich2009


People also ask

What does FileReader onload return?

The FileReader result property returns the file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.

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 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.

How does Javascript FileReader work?

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

Create a closure around the File to capture the current file. Then you can get the filename.

An example: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

Closure to capture the file information.

function parseData(entries){   for (var i=0; i<entries.length; i++) {     reader.onloadend = (function(file) {       return function(evt) {         createListItem(evt, file)       };     })(entries[i]);     reader.readAsText(entries[i]);   } } 

And the called function gets an additional argument

function createListItem(evt, file) {   console.log(evt.target.result)   console.log(file.name); } 
like image 70
ebidel Avatar answered Sep 21 '22 16:09

ebidel