1

使用File System Access API,我将如何访问包含在所选目录的文件夹中的文件?

document.querySelector('button').addEventListener('click', async () => {
  const dirHandle = await window.showDirectoryPicker();
  for await (const entry of dirHandle.values()) {
    if (entry.kind === "file"){
      const file = await entry.getFile();
      const text = await file.text();
      console.log(text);
    }
    if (entry.kind === "directory"){
      /* for file in this directory do something */ 
    }
  }
});
<button>Choose Directory</button>

4

2 回答 2

2

您需要调用该dirHandle.getDirectoryHandle(name, options)方法,并将name参数设置为您的条目的.name.

这是一个示例代码,它将遍历传递的目录并构建它找到的文件的树。

btn.onclick = async (evt) => {
  const out = {};
  const dirHandle = await showDirectoryPicker();  
  await handleDirectoryEntry( dirHandle, out );
  console.log( out );
};
async function handleDirectoryEntry( dirHandle, out ) {
  for await (const entry of dirHandle.values()) {
    if (entry.kind === "file"){
      const file = await entry.getFile();
      out[ file.name ] = file;
    }
    if (entry.kind === "directory") {
      const newHandle = await dirHandle.getDirectoryHandle( entry.name, { create: false } );
      const newOut = out[ entry.name ] = {};
      await handleDirectoryEntry( newHandle, newOut );
    }
  }
}

现场演示编辑代码

于 2021-06-15T05:59:49.820 回答
1

Kaiido 回答的一个小改进:

btn.onclick = async (evt) => {
  const out = {};
  const dirHandle = await showDirectoryPicker();  
  await handleDirectoryEntry( dirHandle, out );
  console.log( out );
};
async function handleDirectoryEntry( dirHandle, out ) {
  for await (const entry of dirHandle.values()) {
    if (entry.kind === "file"){
      const file = await entry.getFile();
      out[ file.name ] = file;
    }
    if (entry.kind === "directory") {
      const newOut = out[ entry.name ] = {};
      await handleDirectoryEntry( entry, newOut );
    }
  }
}

dirHandle.values()返回从 继承的对象列表FileSystemHandle,有两种可能性:要么FileSystemFileHandle要么FileSystemDirectoryHandle

既然const entry已经是一个万一FileSystemDirectoryHandle什么时候不需要打电话 entry.kind"directory"dirHandle.getDirectoryHandle()

于 2021-10-20T07:05:03.380 回答