问题
-
如何选择文件夹
-
如何得到文件夹中的内容
-
如何读到某个文件的内容
实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="selected">选择文件夹</button>
<script>
selected.onclick = async () => {
try {
const handle = await showDirectoryPicker();
const root = await processHandle(handle);
console.log(root); // 输出目录下的所有内容
// test:输出文件夹下的第二个文件内容
const fieHandle = root.children[1];
const file = await fieHandle.getFile();
const reader = new FileReader();
reader.onload = (e) => {
console.log(e.target.result)
}
reader.readAsText(file, 'utf-8');
} catch (error) {
// 用户拒绝
}
async function processHandle(handle) {
if (handle.kind === 'file') {
return handle;
}
handle.children = [];
// 异步迭代器
const itera = handle.entries();
for await (const item of itera) {
handle.children.push(await processHandle(item[1]));
}
return handle;
}
};
</script>
</body>
</html>
打赏作者
您的打赏是我前进的动力
微信
支付宝
进阶技巧🕴️ 对象数组去重
上一篇
评论