文章目录
- 读取文件夹并输出某个文件内容
- 读取文件及输出内容
读取文件夹并输出某个文件内容
效果图
html
<button id="idFolder" class="fs_30 cursor_pointer">选择文件夹</button>
JavaScript
idFolder.onclick = async function () { try { let handle = await showDirectoryPicker(), root = await processHandle(handle), fileHandle = root.child[4], file = await fileHandle.getFile(), reader = new FileReader(); reader.onload = ({ target: { result } }) => { console.log(result); } reader.readAsText(file, 'utf-8'); } catch (error) { console.log(error); // 用户拒绝的处理 } }; async function processHandle(handle) { if (handle.kind === 'file') return handle; handle.child = []; // 得到异步迭代器 let iter = handle.entries(); for await (let item of iter) { handle.child.push(await processHandle(item[1])); } return handle; }
kind: "directory"
directory
文件夹
name: "aText"
aText
文件夹名称
读取文件及输出内容
效果图
html
<button id="idFile" class="fs_30 cursor_pointer">选择文件</button>
JavaScript
idFile.onclick = async function () {
// 创建用于存放文件句柄的变量
let fileHandle = undefined;
// 打开文件选择器,解构返回的数组中的第一个元素
[fileHandle] = await window.showOpenFilePicker();
let file = await fileHandle.getFile(),
reader = new FileReader();
reader.onload = ({ target: { result } }) => {
console.log(result);
}
reader.readAsText(file, 'utf-8');
}