Android filereader异步加载文件后获取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12546775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:56:45  来源:igfitidea点击:

Get filename after filereader asynchronously loaded a file

javascriptandroidcordovafileapi

提问by Sidrich2009

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

欢呼任何建议;)

回答by ebidel

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

在 周围创建一个闭包File以捕获当前文件。然后你可以得到文件名。

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

一个例子: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);
}

回答by Thibault T

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