Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - 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);
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...