Reputation: 1322
I am trying to read all the directories in a given directory which is selected by the user using:
<input type="file" id="directory-chooser" webkitdirectory directory/>
Once the user has selected the desired folder. I am able to fetch all the files using:
var files = document.getElementById('directory-chooser').files;
console.log(files);
The output of this is in the form of:
2: File
lastModifiedDate: Mon Jun 17 2013 17:55:45 GMT+0100 (BST)
name: "."
size: 68
type: ""
webkitRelativePath: "Movies/Superman returns/."
length: 3
As it can be seen, on selecting the directory named Movies
, I get the list of all "files" in it. However, I simply want it to stop looking into the sub-directories and return Superman returns
as a result. Though I want it to keep looking for more first level directories, if there are any.
Upvotes: 2
Views: 1175
Reputation: 4652
You can count the number of "/" inside the path of each file. If the user selects a folder "foo", the paths of the returned files will be:
foo/bar.txt
foo/bar/baz.txt
(...)
Thus, you only want the files that have one forward slash (i.e. they're directly under the selected directory, not in a subdirectory).
Here's the HTML code:
<input type="file" id="directory-chooser" webkitdirectory directory/>
<input type="button" value="files" onclick="showFiles()">
and here's the JS code:
function showFiles() {
var files = document.getElementById('directory-chooser').files;
for (i = 0; i < files.length; i++) {
if (files[i].webkitRelativePath.match(/\//g).length == 1) {
// The file in question is not in a subfolder, so show it
console.log(files[i]);
}
}
}
And finally, here's a working jsFiddle:
Upvotes: 2