---

title: "File System Access:showDirectoryPicker 目录选择与递归遍历"

keywords:

  • showDirectoryPicker
  • FileSystemDirectoryHandle
  • 递归遍历
  • 权限与持久化
  • OPFS

description: "介绍目录选择与遍历读取文件的流程,权限与用户交互、递归遍历与过滤实现,并与持久化策略协同,提供示例与安全建议。"

categories:

  • 应用软件
  • 办公软件

---

概述

showDirectoryPicker 允许用户选择本地目录并返回 FileSystemDirectoryHandle,可遍历其子文件与子目录。适用于批量导入、资源管理与编辑器场景,需在安全上下文并处理权限与交互。

示例:递归遍历目录

async function pickAndWalk() {
  const dir = await window.showDirectoryPicker()
  const files = []
  async function walk(handle, path = '') {
    for await (const [name, child] of handle.entries()) {
      const p = `${path}/${name}`
      if (child.kind === 'file') {
        const file = await child.getFile()
        files.push({ path: p, size: file.size, type: file.type })
      } else if (child.kind === 'directory') {
        await walk(child, p)
      }
    }
  }
  await walk(dir)
  return files
}

工程建议

  • 权限与 UX:清晰提示用途;处理用户取消与错误;在用户手势触发。
  • 过滤与安全:过滤可接受的类型与大小,避免执行不可信内容;对敏感文件谨慎处理。
  • 持久化与协作:结合 navigator.storage.persist() 与 OPFS;缓存索引与元数据。

参考与验证

  • MDN File System Access 文档:https://developer.mozilla.org/docs/Web/API/File_System_Access_API
  • web.dev 目录选择指南:https://web.dev/articles/file-system-access
  • Chrome 文档:https://developer.chrome.com/docs/web-platform/file-system-access/

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部