JS选择文件夹后怎么递归获取所有子文件路径
详解在浏览器端使用 JavaScript 选择文件夹后获取所有子文件路径的三种方法:showDirectoryPicker 异步递归、input webkitdirectory 读取 webkitRelativePath 及拖拽 webkitGetAsEntry 递归,包含完整代码与常见问题辨析。
在浏览器端用 JavaScript 选择文件夹并获取全部子文件路径,核心取决于你采用哪套选择接口:如果使用现代的 window.showDirectoryPicker(),浏览器只返回顶层目录句柄,需要自己写异步递归函数逐层读取并拼接路径;如果使用兼容性更广的 <input type="file" webkitdirectory>,浏览器会在选择时自动递归出所有文件,直接读取每个 File 对象的 webkitRelativePath 属性即可。如果涉及把文件夹拖入页面,则通过 webkitGetAsEntry() 循环读取目录项并递归。
先分清两类选择方式:要不要自己写递归
很多人在检索“JS 选择文件夹获取子文件路径”时容易卡住,原因在于浏览器提供了两套机制完全不同的文件夹选择接口:<input type="file" webkitdirectory> 和 window.showDirectoryPicker()。两者虽然都能让用户挑一个本地文件夹,但返回的数据结构决定了后续是否需要手写递归。
使用 <input webkitdirectory> 时,浏览器底层会在确认选择的一瞬间自行扫描所有子目录,最后把全部文件铺平放到 input.files(一个 FileList)中。也就是说,你拿到的已经是全部后代文件,不需要再遍历目录树,只要读取每个 File 实例的 webkitRelativePath 就能得到相对路径。
使用 window.showDirectoryPicker() 时,浏览器出于性能和权限考虑,不会预先扫描整个目录树,而是只返回一个代表根目录的 FileSystemDirectoryHandle。此时你必须自己编写异步递归函数,通过目录句柄迭代子项,遇到文件就拼接并保存路径,遇到子目录就继续向下递归。
方法一:用 showDirectoryPicker() 手动递归获取子文件路径
如果你的应用面向现代桌面浏览器(如 Chrome、Edge 等基于 Chromium 的浏览器),且文件夹里可能有成千上万个文件、需要跳过 node_modules 或 .git 这类无关目录,推荐使用 File System Access API 提供的 window.showDirectoryPicker()。
使用前必须满足的两个前提
- 安全上下文:页面必须运行在
https://协议或本地调试地址http://localhost(以及127.0.0.1)下;直接双击本地file://打开或普通http://局域网地址通常无法调用该接口。 - 用户手势触发:
showDirectoryPicker()只能在按钮click等明确的用户交互回调中调用,不能在页面加载时自动弹出。
完整可运行示例
下面这段完整的 HTML 页面代码可以直接保存为 picker-demo.html,通过本地开发服务器(例如 http://localhost)打开后点击按钮即可测试。代码同时演示了忽略常见大目录、保留句柄以便按需读取文件内容,以及处理用户取消选择的异常。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>showDirectoryPicker 递归获取文件路径</title>
</head>
<body>
<button id="pickBtn" type="button">选择文件夹</button>
<pre id="output"></pre>
<script>
const IGNORED_DIRS = new Set(['node_modules', '.git', 'dist']);
async function collectFilePaths(dirHandle, parentPath = '', results = []) {
for await (const entry of dirHandle.values()) {
const currentPath = parentPath ? `${parentPath}/${entry.name}` : entry.name;
if (entry.kind === 'file') {
results.push({
path: currentPath,
handle: entry
});
} else if (entry.kind === 'directory') {
if (IGNORED_DIRS.has(entry.name)) {
continue;
}
await collectFilePaths(entry, currentPath, results);
}
}
return results;
}
document.getElementById('pickBtn').addEventListener('click', async () => {
const output = document.getElementById('output');
if (!('showDirectoryPicker' in window)) {
output.textContent = '当前浏览器不支持 showDirectoryPicker(),请改用 webkitdirectory 方案。';
return;
}
try {
const rootHandle = await window.showDirectoryPicker({ mode: 'read' });
// 若希望路径包含最外层文件夹名,将第二参数改为 rootHandle.name
const items = await collectFilePaths(rootHandle, rootHandle.name);
const paths = items.map(item => item.path).sort();
output.textContent = paths.length
? paths.join('\n')
: '所选文件夹内没有符合条件的文件。';
} catch (err) {
if (err.name === 'AbortError') {
output.textContent = '已取消选择文件夹。';
} else {
output.textContent = `读取失败:${err.message}`;
}
}
});
</script>
</body>
</html>
path 和 entry(FileSystemFileHandle),不要急着对每个文件调用 await entry.getFile()。等到用户真正点击预览或准备上传某几个文件时,再按需调用 handle.getFile(),能明显减少数千个文件场景下的卡顿。
方法二:用 <input webkitdirectory> 读取 webkitRelativePath
如果页面需要兼容 Safari、Firefox、移动端浏览器,或者无法保证始终在 HTTPS 下运行,那么传统的 <input type="file" webkitdirectory> 是更稳妥的选择。虽然 webkitdirectory 早期带浏览器前缀,但目前主流桌面浏览器均已支持这一属性。
需要注意的关键点是:把目录选进来之后,change 事件里的 event.target.files 已经包含了所有层级下的全部文件,此时不需要再写递归函数,直接遍历 FileList 并读取 file.webkitRelativePath 即可。
<input id="folderInput" type="file" webkitdirectory multiple>
<pre id="inputOutput"></pre>
<script>
const folderInput = document.getElementById('folderInput');
const inputOutput = document.getElementById('inputOutput');
folderInput.addEventListener('change', (event) => {
const files = Array.from(event.target.files || []);
const paths = files
.map(file => file.webkitRelativePath || file.name)
.sort();
inputOutput.textContent = paths.join('\n');
// 清空 value,确保用户下次选择同一个文件夹时仍能触发 change 事件
event.target.value = '';
});
</script>
使用 webkitdirectory 时有两个常见限制要提前考虑。第一,input.files 只能列出文件,如果文件夹里存在空子目录,它不会出现在列表中。第二,如果你要把这批扁平路径还原成树形菜单给用户展示,可以对 file.webkitRelativePath.split('/') 按斜杠拆分后再构建嵌套对象,这属于“把路径数组转成树”,而不是向文件系统递归。
容易混淆的说法辨析
围绕“JS 选择文件夹获取子文件路径”,网上常见几类容易混淆的说法。它们各自带有一定道理,但如果直接照搬,在实际开发时往往会踩坑。
混淆一:“浏览器 JS 选中文件夹后能拿到本机的绝对路径”
这种说法只在某些特定宿主环境(如 Electron、Node.js 桌面端集成环境)下成立;在标准网页浏览器中并不成立。出于沙箱安全限制,浏览器不会把用户磁盘的真实绝对路径(例如 C:\Users\Alice\Desktop\demo\src\app.js 或 /Users/alice/demo/src/app.js)暴露给网页脚本。你在网页端拿到的始终是以所选文件夹为根起点的相对路径,例如 "demo/src/app.js"。
混淆二:“用了 <input webkitdirectory> 之后,也要手写递归才能看到子文件夹里的文件”
写过桌面端程序的人很容易按惯性这样理解,因为在 Node.js 的 fs.readdir 中,一次读取只返回当前一层。但在 <input webkitdirectory> 中,input.files 已经把子目录全部打平放进来了。如果你在 change 事件里发现只拿到了文件名(file.name 为 "app.js")而没有路径,原因通常不是“漏了递归”,而是误读了 file.name,应该改读 file.webkitRelativePath。
混淆三:“拖拽文件夹用 readEntries() 读一次就够了”
在拖放少于几十个文件的小文件夹做测试时,调用一次 reader.readEntries() 确实能返回全部条目,因此看起来没问题。但按照 Chromium 等浏览器的实现,单次 readEntries() 调用返回的条目数量存在上限(常见为每次最多返回 100 条)。一旦文件夹下有几百个文件或目录,只调用一次就会静默丢失其余文件,必须用循环一直读到返回空数组为止。
方法三(补充场景):拖拽文件夹时用 webkitGetAsEntry() 递归
当业务要求把本地文件夹直接拖入网页区域时,既用不到 <input> 也不用 showDirectoryPicker(),而是要在 drop 事件中读取 e.dataTransfer.items,并通过 item.webkitGetAsEntry() 拿到目录入口,再使用 createReader() 递归读取。
<div id="dropZone" style="padding: 32px; border: 2px dashed #8A9478;">
把文件夹拖到这里
</div>
<pre id="dropOutput"></pre>
<script>
const dropZone = document.getElementById('dropZone');
const dropOutput = document.getElementById('dropOutput');
// 必须循环调用 readEntries,直到返回空数组,防止单次返回受限导致漏文件
function readAllEntries(directoryReader) {
return new Promise((resolve, reject) => {
const entries = [];
function readBatch() {
directoryReader.readEntries((batch) => {
if (batch.length === 0) {
resolve(entries);
} else {
entries.push(...batch);
readBatch();
}
}, reject);
}
readBatch();
});
}
async function walkEntry(entry, results = []) {
if (entry.isFile) {
// entry.fullPath 形如 "/my-app/src/index.js",去掉开头的 "/"
results.push(entry.fullPath.replace(/^\//, ''));
return results;
}
if (entry.isDirectory) {
const reader = entry.createReader();
const children = await readAllEntries(reader);
for (const child of children) {
await walkEntry(child, results);
}
}
return results;
}
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
});
dropZone.addEventListener('drop', async (e) => {
e.preventDefault();
const items = Array.from(e.dataTransfer.items || []);
const allPaths = [];
for (const item of items) {
const entry = item.webkitGetAsEntry && item.webkitGetAsEntry();
if (entry) {
await walkEntry(entry, allPaths);
}
}
dropOutput.textContent = allPaths.sort().join('\n');
});
</script>
三种方案怎么选,以及实用注意事项
实际项目里没有哪一种方案适合所有场景,可以根据目标浏览器范围、文件夹体积以及是否需要反向写入本地来决定。
| 对比维度 | showDirectoryPicker() | input[webkitdirectory] | 拖拽 webkitGetAsEntry() |
|---|---|---|---|
| 是否需要手写递归 | 需要(async 迭代目录句柄) |
不需要(浏览器已自动铺平) | 需要(循环 readEntries 递归) |
| 浏览器兼容性 | 现代桌面 Chromium 内核支持较好;Safari/Firefox 受限 | 桌面主流浏览器普遍支持,兼容性最好 | 主流桌面浏览器支持,移动端通常无文件夹拖拽 |
| 过滤大目录(如 node_modules) | 可在进入子目录前跳过,不扫描内部文件 | 无法提前跳过,只能在扫描后过滤结果数组 | 可在判断 entry.name 后跳过子目录 |
| 能否感知空文件夹 | 可以 | 不可以(只返回文件) | 可以 |
| 适用安全上下文 | 必须在 HTTPS 或 localhost 下使用 | 普通 HTTP / HTTPS 均可使用 | 普通 HTTP / HTTPS 均可使用 |
- 保持分隔符统一:无论在 Windows 还是 macOS 上,自己拼接路径时统一使用正斜杠
/,这样与webkitRelativePath返回的格式完全一致,前后端匹配或展示目录树时不需要额外做反斜杠替换。 - 跳过系统隐藏文件:macOS 文件夹常带有
.DS_Store,项目目录常带有.git或node_modules。递归或过滤阶段把这些名字排除掉,既能减少误报,也能防止前端遍历几万个依赖文件造成页面卡死。 - 提供降级回退:在需要稳定交付给所有用户的网页里,可以先判断
'showDirectoryPicker' in window;不支持时自动隐藏该按钮并切换成<input type="file" webkitdirectory>,两条路径共用同一套后续的路径列表渲染或上传逻辑即可。
JS批量获取页面所有图片src地址的代码实现
2026-11-16 15:04:52
原生JS实现复选框全选与取消全选功能
2026-11-16 14:27:17
iOS Safari中JS设置overflow:hidden禁止滑动失效怎么办
2026-11-16 13:42:35
JavaScript TextEncoder API处理中文编码教程
2026-11-16 13:24:19
JavaScript使用btoa和atob实现Base64编码解码及中文乱码解决
2026-11-16 13:24:05








