js showOpenFilePicker showSaveFilePicker showDirectoryPicker API

选择文件,获取文件句柄

btn.addEventListener("click", async (e) => {
try {
const hFiles = await window.showOpenFilePicker({
types: [
{
description: "文本文件",
accept: {
"text/plain": [".txt"],
},
},
],
});
if (!hFiles || !hFiles.length) return;
const hFile = hFiles[0];
l(hFile);
} catch (error) {
console.error(error);
}
});

从文件句柄中获取文件的内容

const file = await hFile.getFile();
const r = new FileReader();
r.readAsText(file);
r.onload = (e) => {
const fileData = e.target.result;
l(fileData);
};
// or
l(await file.text());
l(await file.arrayBuffer());
l(await file.stream().getReader().read());

使用文件句柄写入内容

const w$ = await hFile.createWritable();
await w$.write('hello ');
await w$.write('world');
await w$.close();

使用 showSaveFilePicker

const hFile = await window.showSaveFilePicker();
const w = await hFile.createWritable();
await w.write('new data');
await w.close();

打开目录

const hDir = await window.showDirectoryPicker();
// 打印文件名,和类型
for await (const it of hDir.values()) {
l('[[ %s ]] is %s', it.name, it.kind);
}
// 打印文件名和句柄
for await (const [name, handle] of hDir) {
l(name, handle);
}

在目录句柄中创建一个新的目录(名叫"NewDir"的目录),返回新创建目录的句柄

const hNewDir = await hDir.getDirectoryHandle("NewDir", {
create: true,
});

在目录句柄中创建一个新的文件(名叫"newFile.txt"的文件),返回新创建文件的句柄

const hNewFile = await hDir.getFileHandle("newFile.txt", {
create: true,
});

往新创建的文件中写入内容

const w$ = await hNewFile.createWritable();
await w$.write('在新创建的文件中写入内容');
await w$.close();

遍历整个目录

const scanDir = async (root, hDir) => {
for await (const [name, handle] of hDir) {
const path = await root.resolve(handle);
if (handle instanceof FileSystemDirectoryHandle) {
l("./%s/", path.join("/"));
scanDir(root, handle);
} else l("./%s", path.join("/"));
}
};
scanDir(hDir, hDir);

删除目录中指定的文件

await hDir.removeEntry('newFile.txt');

在目录中递归删除子目录

await hDir.removeEntry("Debug", { recursive: true });

isSameEntry

如果是同一文件或目录则返回true

const hDir = await window.showDirectoryPicker();
const hFile = await hDir.getFileHandle("3.txt");
console.log( await hFile.isSameEntry(hFile) ); // true
console.log( await hDir.isSameEntry(hDir) ); // true
console.log( await hFile.isSameEntry(hDir) ); // false
console.log( await hDir.isSameEntry(hFile) ); // false

resolve

获取文件在目录中的路径

const hDir = await window.showDirectoryPicker();
const hFile = await hDir.getFileHandle("3.txt");
console.log( await hDir.resolve(hFile) ) // ["3.txt"]

See also:

posted @   Ajanuw  阅读(2262)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2018-10-09 Nestjs 获取cookie
点击右上角即可分享
微信分享提示