You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过文件系统访问API的window.showDirectoryPicker()获取选中目录完整路径

出于用户隐私安全限制,File System Access API 设计上不会向Web页面暴露本地文件系统的真实完整绝对路径,因此FileSystemDirectoryHandle原生没有提供类似fullpath的属性,也没有官方方法可以直接获取到完整路径。

不同场景替代方案
  • 仅需要获取选中文件夹本身的名称
    直接调用原生name属性即可:

    const dirHandle = await window.showDirectoryPicker()
    const currentDirName = dirHandle.name
    

    该属性仅返回选中文件夹自身的名称,不包含任何上级目录路径信息。

  • 需要使用相对于选中根目录的层级路径
    如果是从选中的根目录开始遍历子文件/子目录,可以自行拼接层级相对路径,示例如下:

    // 递归遍历目录,拼接相对根目录的路径
    async function traverseDir(handle, rootRelativePath = '') {
      const currentPath = rootRelativePath ? `${rootRelativePath}/${handle.name}` : handle.name
      if (handle.kind === 'directory') {
        for await (const entry of handle.values()) {
          await traverseDir(entry, currentPath)
        }
      } else {
        console.log('当前文件相对路径:', currentPath)
      }
    }
    
    const rootDirHandle = await window.showDirectoryPicker()
    await traverseDir(rootDirHandle)
    

    拼接出的路径仅相对于你最开始选中的根目录,不会包含用户本地的系统级根路径信息。

  • 需要获取用户本地真实绝对路径
    没有原生方案可以实现,若确实需要该信息,只能引导用户手动输入补充。

内容的提问来源于stack exchange,提问作者dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:36:03