3

所以我正在尝试创建一个文件投放器 Web 应用程序。现在,用户可以将文件拖放到屏幕上,我可以读取它们,包括已拖放目录中的所有文件。但是,我不知道脚本何时完成读取文件。

一些代码:

第一个函数处理“drop”事件,并将遍历每个文件并将其发送到另一个函数,该函数将读取其内容。

function readDrop( evt )
{
    for( var i = 0; i < evt.dataTransfer.files.length; i++)
    {
        var entry = evt.dataTransfer.items[i].webkitGetAsEntry();

        if(entry)
            readContents(entry, "");
    }

    //Do stuff after all files and directories have been read.
}

这个函数是一个递归的 FileEntry 阅读器。如果是文件,我会读取 FileEntry。如果是目录,它会循环遍历内容并通过这个函数传递。

function readContents(entry, path)
{
    if( entry.isFile )
    {
        readFileData( entry, path, function(fileData)
        {
            _MyFiles.push( fileData );
        });
    }
    else if( entry.isDirectory )
    {
        var directoryReader = entry.createReader();
        var path = path + entry.name;

        directoryReader.readEntries(function(results)
        {
            for( var j = 0; j < results.length; j++ )
            {
                readContents(entry, path);
            }

        }, errorHandler)
    }
}

这是我读取文件的功能。回调只是将 fileData 对象推送到全局数组

function readFileData(entry, path, callback)
{
    var fileData = {"name": entry.name, "size": 0, "path": path, "file": entry};

    entry.file(function(file)
    {
        fileData["size"] = file.size;
        callback( fileData );
    }
}

我不确定从这里去哪里,以便在读取所有文件和目录后进行回调。

4

2 回答 2

9

FileSystem API 似乎不太适合完全递归遍历的任务,这可能是其他供应商不采用它的部分原因。无论如何,通过 Promises 的神秘组合,我想我能够实现这个目标:

    function traverse_directory(entry) {
        let reader = entry.createReader();
        // Resolved when the entire directory is traversed
        return new Promise((resolve_directory) => {
            var iteration_attempts = [];
            (function read_entries() {
                // According to the FileSystem API spec, readEntries() must be called until
                // it calls the callback with an empty array.  Seriously??
                reader.readEntries((entries) => {
                    if (!entries.length) {
                        // Done iterating this particular directory
                        resolve_directory(Promise.all(iteration_attempts));
                    } else {
                        // Add a list of promises for each directory entry.  If the entry is itself 
                        // a directory, then that promise won't resolve until it is fully traversed.
                        iteration_attempts.push(Promise.all(entries.map((entry) => {
                            if (entry.isFile) {
                                // DO SOMETHING WITH FILES
                                return entry;
                            } else {
                                // DO SOMETHING WITH DIRECTORIES
                                return traverse_directory(entry);
                            }
                        })));
                        // Try calling readEntries() again for the same dir, according to spec
                        read_entries();
                    }
                }, errorHandler );
            })();
        });
    }

    traverse_directory(my_directory_entry).then(()=> {
        // AT THIS POINT THE DIRECTORY SHOULD BE FULLY TRAVERSED.
    });
于 2016-01-05T19:29:23.647 回答
4

根据 drarmstr 的回答,我修改了函数以符合 Airbnb ESLint 标准,并想对其使用和结果做一些进一步的评论

这是新功能:

function traverseDirectory(entry) {
  const reader = entry.createReader();
  // Resolved when the entire directory is traversed
  return new Promise((resolve, reject) => {
    const iterationAttempts = [];
    function readEntries() {
      // According to the FileSystem API spec, readEntries() must be called until
      // it calls the callback with an empty array.  Seriously??
      reader.readEntries((entries) => {
        if (!entries.length) {
          // Done iterating this particular directory
          resolve(Promise.all(iterationAttempts));
        } else {
          // Add a list of promises for each directory entry.  If the entry is itself
          // a directory, then that promise won't resolve until it is fully traversed.
          iterationAttempts.push(Promise.all(entries.map((ientry) => {
            if (ientry.isFile) {
              // DO SOMETHING WITH FILES
              return ientry;
            }
            // DO SOMETHING WITH DIRECTORIES
            return traverseDirectory(ientry);
          })));
          // Try calling readEntries() again for the same dir, according to spec
          readEntries();
        }
      }, error => reject(error));
    }
    readEntries();
  });
}

这是一个放置事件处理程序:

function dropHandler(evt) {
  evt.preventDefault();
  const data = evt.dataTransfer.items;
  for (let i = 0; i < data.length; i += 1) {
    const item = data[i];
    const entry = item.webkitGetAsEntry();
    traverseDirectory(entry).then(result => console.log(result));
  }
}

最后的result变量包含一个数组,反映了您拖放的文件夹的树结构。

例如,这是我自己网站的一个 git repo,运行了上面的代码:

在此处输入图像描述

这是用于比较的 Git 存储库https://github.com/tomjn/tomjn.com

于 2018-04-25T19:58:16.583 回答