2012-04-19 115 views
4

我使用文件输入和webkit目录加载了一个目录,如下所述。HTML5文件系统 - 如何使用目录阅读器读取目录?

<input id="file_input" type="file" webkitdirectory directory /> 

选择目录后,我可以读取文件大小和其他信息。我的问题是如何使用DirectoryReader接口读取此目录。

我试着用下面的代码,但没有成功。 results.length成为零。我错过了什么?

window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, function(fs) { 
     var dirReader = fs.root.createReader(); 
     var entries = []; 
     // Call the reader.readEntries() until no more results are returned. 
     var readEntries = function() { 
      dirReader.readEntries(function(results) { 
       // If no more results are returned, we're done. 
       if (!results.length) { 
        // Sort list by name of entry. 
        entries.sort(function(a, b) { 
         return a.name < b.name ? -1 : 
         b.name < a.name ? 1 : 0; 
        }); 
        // listResults(entries); // Render the list. 
       } else { 
        // Add in these results to the current list. 
        entries = entries.concat(toArray(results)); 
        readEntries(); 
       } 
      }, errorHandler); 
     }; 
     readEntries(); // Start reading the directory. 
    }, errorHandler); 

任何帮助表示赞赏。

+2

检查了您想接受的答案的绿色轮廓箭头。 – 2013-06-14 02:04:26

回答

14

要读取目录的内容:

fs.root.getDirectory('Documents', {}, function(dirEntry){ 
    var dirReader = dirEntry.createReader(); 
    dirReader.readEntries(function(entries) { 
    for(var i = 0; i < entries.length; i++) { 
     var entry = entries[i]; 
     if (entry.isDirectory){ 
     console.log('Directory: ' + entry.fullPath); 
     } 
     else if (entry.isFile){ 
     console.log('File: ' + entry.fullPath); 
     } 
    } 

    }, errorHandler); 
}, errorHandler); 

在上面的代码中,isDirectory和ISFILE特性,以便分别获得用于目录和文件不同的输出,使用。此外,我们使用fullPath属性来获取条目的完整路径,而不仅仅是它的名称。

来自:http://net.tutsplus.com/tutorials/html-css-techniques/toying-with-the-html5-filesystem-api/

+0

感谢您的快速响应。 – Joe 2012-04-19 18:53:43

+1

当我尝试使用我的根目录名而不是'Documents'时,我收到FileError.NOT_FOUND_ERR错误。 – Joe 2012-04-19 19:04:10

+0

我可以查看您的新代码吗? – fdicarlo 2012-04-19 19:10:43