我正在尝试读取放置的文件夹的目录结构,但是我遇到了chrome无法在不加延迟的情况下报告对象中正确数量的项目的问题。
对于我来说,该对象可能在第一次和第二次记录之间丢失一个项目,然后在第三次记录时获得它,这没有任何意义。
任何帮助将不胜感激。
更新:我进行了更多测试,发现即使从现有数组复制值而不是读取文件结构,我仍然遇到相同的问题。
这是 jsfiddle ,可以更清楚地显示问题。
这似乎几乎是solution,但是,在两种情况下,如果我拖动多个子文件夹而不是父文件夹,它们都会触发多次。我希望能够拖动一个子文件夹的文件夹或选择一个子文件夹,并使该事件在末尾触发一次,所以基本上在for循环末尾触发。
// Works correctly
console.log(itemList);
// Doesn't log anything
Object.keys(itemList).forEach(function(key)
{
console.log('where is this?', key, itemList[key]);
});
// Works correctly on my local server with 0ms delay
// and on jsfiddle with 50ms
setTimeout(function()
{
Object.keys(itemList).forEach(function(key)
{
console.log('ms delay', key, itemList[key]);
});
},50);
答案 0 :(得分:0)
好的,我终于找到了可行的解决方案。
const target = document.getElementById('dropTarget');
let itemList = [];
target.ondragover = function(evt) {
evt.preventDefault();
}
target.ondrop = function(e) {
e.preventDefault();
let items = e.dataTransfer.items;
function scanFiles(item, index) {
return new Promise(function(resolve) {
if (item.isFile) {
itemList.push(item.fullPath);
resolve();
} else if (item.isDirectory) {
let directoryReader = item.createReader();
directoryReader.readEntries(function(entries) {
Promise.all(entries.map(scanFiles)).then(resolve);
});
}
})
}
var p = Promise.all(Array.from(items, item => scanFiles(item.webkitGetAsEntry())));
p.then(function() {
//console.log(itemList);
Object.keys(itemList).forEach(function(key) {
console.log(key, itemList[key]);
});
})
}