本文介绍了如何使用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对象、应用相关方法、访问对象相关属性 。
具体代...