Get filename after filereader asynchronously loaded a file

梦想的初衷 提交于 2019-11-27 12:02:31

问题


i am loading several files in a directory to parse some data from them. This works great so far, but i would like to know wich 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 wich 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);
  }
}

cheers for any suggestions ;)


回答1:


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



回答2:


The following source code add an attribute to the file reader

    for(i=0; i < files.length; i++)
    {
        var fileReader = new FileReader();
        fileReader.onload = function(file)
        {
              // DO what you need here
              // file name = file.target.fileName
        } // end of reader load
        fileReader.fileName = files[i].name;
        fileReader.readAsBinaryString(files[i]);
    }



回答3:


Another way to solve this problem is to read the filename after the onload-event with the onloadend-event like this:

for (var i = 0; i < files.length; i++) {

    var fileReader = new FileReader();

    fileReader.fileName = files[i].name;

    fileReader.onload = function () {
        /* do something with file */
    }

    fileReader.onloadend = function () {
        console.log(fileReader.fileName); // here you can access the original file name
    }

    fileReader.readAsText(files[i]);

}


来源:https://stackoverflow.com/questions/12546775/get-filename-after-filereader-asynchronously-loaded-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!