概述
File System Access API 提供更直接的本地文件读写能力,适合编辑器与导入导出场景。需在安全上下文(HTTPS)下启用,并处理权限与用户交互。
用法与示例
打开与读取
```js
const [handle] = await window.showOpenFilePicker({
types: [{ description: 'Text', accept: { 'text/plain': ['.txt'] } }]
})
const file = await handle.getFile()
const text = await file.text()
```
保存与写入
```js
const handle = await window.showSaveFilePicker({
types: [{ description: 'Text', accept: { 'text/plain': ['.txt'] } }]
})
const writable = await handle.createWritable()
await writable.write('Hello World')
await writable.close()
```
工程建议
- 权限与 UX:在读写前提示用户操作意图;处理取消与异常,避免数据丢失。
- 持久化:结合 `navigator.storage.persist()` 与 OPFS 提升可靠性;对不支持浏览器回退到下载/上传方案。
- 安全:校验文件类型与内容;避免执行不可信代码与脚本。
参考与验证
- MDN File System Access 文档:https://developer.mozilla.org/docs/Web/API/File_System_Access_API
- web.dev 指南:https://web.dev/articles/file-system-access
- Chrome 平台文档:https://developer.chrome.com/docs/web-platform/file-system-access/

发表评论 取消回复