`title: File System Access 文件选择与保存对话框最佳实践``categories: Web 开发/前端/数据管理``keywords: File System Access API,showOpenFilePicker,showSaveFilePicker,OPFS,编辑``description: 使用文件选择与保存对话框在浏览器端实现本地文件读写,结合 OPFS 与应用内工作流,确保权限与兼容性。`选择与读取async function openText() {

const [h] = await window.showOpenFilePicker({ types: [{ description: 'Text', accept: { 'text/plain': ['.txt'] } }] });

const file = await h.getFile();

return await file.text();

}

保存与写入async function saveText(name, content) {

const h = await window.showSaveFilePicker({ suggestedName: name, types: [{ description: 'Text', accept: { 'text/plain': ['.txt'] } }] });

const w = await h.createWritable();

await w.write(new Blob([content], { type: 'text/plain; charset=utf-8' }));

await w.close();

}

与 OPFS 协作读入后持久化到 OPFS,供离线编辑与索引。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部