前端选文件夹以及内容

关键点

  • 如何打开文件夹选择框
  • 如何获取其中的子文件(夹)
  • 如何获取文件或者文件内容
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button>打开文件夹</button>
  <script>
    const btn = document.querySelector('button');
    btn.onclick = async () => {
      const handle = await showDirectoryPicker();
      await processHandle(handle);
      console.log(handle);
      const fileHandle = await handle.children[0]
      const file = await fileHandle.getFile();
      const fileReader = new FileReader();
      fileReader.onload = async (e) => {
        console.log(e.target.result);
      }
      fileReader.readAsText(file);
    }


    async function processHandle (handle) {
      // 如果是文件先不处理
      if (handle.kind === 'file') {
        return
      }
      handle.children = [];
      const iter = await handle.entries(); //异步迭代器
      for await (const entry of iter) {
        console.log(entry);
        await processHandle(entry[1])
        handle.children.push(entry[1]);
      }
    }
  </script>
</body>

</html>

showDirectoryPicker 兼容性问题

兼容性截图

Top