拖拽文件夹上传文件

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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();
readerEntries(dirReader, path, item)
}
}

// readEntries 每次最多返回100个,需要重复调用
// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries
functoin readerEntries (dirReader, path, item) {
dirReader.readEntries(entries => {
for (var i = 0; i < entries.length; i++) {
traverseFileTree(entries[i], path + item.name + '/')
}
if (entries.length) readerEntries(dirReader, path, item)
})
},

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

兼容性

CanIUse

参考