I want to allow users dragging and uploading directory and files.
i know i could create
<input type="file" multiple />
<!-- for files/multiple files upload-->
and
<input type="file" directory mozDirectory webkitDirectory />
<!-- for directory uploads -->
i tried detecting while user is dragging the item if it is a directory or file and setting directory attribute depending on that, but turns out that javascript doesn't allow you to check that.
also i have seen on lot of websites that users are able to drag both files and directories together and even multiple directories.
how can i achieve that?
Dragging and droppping of folders is available in Chrome >= 21
Here's what you need (Not tried, but it can give you the idea):
function traverseFileTree(item, path) {
path = path || "";
if (item.isFile) {
// Get file
item.file(function(file) {
console.log("File:", path + file.name);
});
} else if (item.isDirectory) {
// Get folder contents
var dirReader = item.createReader();
dirReader.readEntries(function(entries) {
for (var i=0; i<entries.length; i++) {
traverseFileTree(entries[i], path + item.name + "/");
}
});
}
}
dropArea.addEventListener("drop", function(event) {
event.preventDefault();
var items = event.dataTransfer.items;
for (var i=0; i<items.length; i++) {
// webkitGetAsEntry is where the magic happens
var item = items[i].webkitGetAsEntry();
if (item) {
traverseFileTree(item);
}
}
}, false);
More information can be found here
Answer taken from here