一共分为四个步骤
1.如何弹出文件夹选择框
<button>打开文件夹</button>
<script>
const btn = document.querySelector('button')
btn.onclick = function ()
{
//只需要这一个方法即可
showDirectoryPicker()
}
</script>
这样就可以实现弹出文件夹
2.如何获取文件夹中的内容
<body>
<button>打开文件夹</button>
<script>
const btn = document.querySelector('button')
btn.onclick = async function ()
{
//句柄
const handle = await showDirectoryPicker();
await processHandle(handle);
}
async function processHandle (handle)
{
if (handle.kind === 'file') {
return;
}
//entries ;异步迭代器还有一个values 可自行打印
const entries = await handle.values();
handle.children = []
for await (const subHandle of entries) {
handle.children.push(subHandle)
await processHandle(subHandle)
}
}
</script>
</body>
3.如何读取文件内容
<body>
<button>打开文件夹</button>
<script>
const btn = document.querySelector('button')
btn.onclick = async function ()
{
//句柄
const handle = await showDirectoryPicker();
await processHandle(handle);
const fileHandle = handle.children[0];
const file = await fileHandle.getFiles();
const reader = new FileReader();
reader.onload = (e) =>{
console.log(e.target.value);
}
reader.readAsText(file);
//可自行打印看
console.log(handle);
}
async function processHandle (handle)
{
if (handle.kind === 'file') {
return;
}
//entries ;异步迭代器还有一个values 可自行打印
const entries = await handle.values();
handle.children = []
for await (const subHandle of entries) {
handle.children.push(subHandle)
await processHandle(subHandle)
}
}
</script>
</body>
4.如何实现代码着色
可以直接用一个第三方库实现 highlight.js
这样就完成了!!!!