本文介绍了如何使用JavaScript在用户点击按钮后,通过`window.showDirectoryPicker()`获取文件夹中的所有文件和子文件夹,利用递归遍历,并使用FileReader读取文件内容。 摘要生成于 ,由 DeepSeek-R1 满血版支持, < meta charset = " UTF-8 " > < meta name = " viewport " content = " width=device-width, initial-scale=1.0 " > < title > 获取文件夹中的所有文件和子文件夹 </ title > </ head > < button > 打开文件夹 </ button > </ body > < script > * 获取按钮元素并添加点击事件处理函数 var btn = document . querySelector ( 'button' ) ; btn . onclick = async function ( ) { // 显示文件选择器 const directoryHandle = await window . showDirectoryPicker ( ) ; // 处理目录 await proecssHandle ( directoryHandle ) ; // 获取目录下的第三个子项(即文件) const files = await directoryHandle . children [ 2 ] ; // 获取文件 const file = await files . getFile ( ) ; // 创建文件读取器 const fileReader = new FileReader ( ) ; // 当文件读取完成时执行回调函数 fileReader . onload = function ( e ) { console . log ( e . target . result ) ; // 读取文件内容 fileReader . readAsText ( file ) ; // 输出用户选择的目录 console . log ( '用户选择的目录是:' , directoryHandle ) ; async function proecssHandle ( handle ) { // 如果是文件则直接返回 if ( handle . kind === 'file' ) { return ; // 初始化子文件夹数组 handle . children = [ ] ; // 获取文件夹中的所有文件和子文件夹 let iter = await handle . entries ( ) ; // 遍历文件夹中的所有文件和子文件夹 for await ( let entry of iter ) { // 递归调用处理函数 await proecssHandle ( entry [ 1 ] ) ; // 将子文件夹添加到父文件夹的子文件夹数组中 handle . children . push ( entry [ 1 ] ) ; </ script > </ html >
如下所示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> [removed] function init(){
你不能直接使用 JavaScript 获取 本地 文件夹 中的 所有 文件 ,因为它需要被浏览器隔离,以防止访问本地系统 文件 。 然而,如果你想在 Web 应用程序中使用本地 文件 ,你可以使用 File API,它允许你从用户选择的 文件 中读取数据。 这是一个例 : <input type="file" id="input" multiple /> <script> var input...
二、FileSystemObject编程 使用FileSystemObject 对象进行编程很简单,一般要经过如下的步骤: 创建FileSystemObject对象、应用相关方法、访问对象相关属性 。 具体代...