Chrome 浏览器可以读写本地文件了,虽说是实验api,但是基本86+已经支持了

目前该API只能在https域名上使用!!!

实现逻辑:

1.唤醒浏览器选择文件夹、文件权限

复制代码
document.getElementById('button').addEventListener('click', async () => {
 getFile()
    });
 async function getFile () {
 // 打开文件选择器   记住FileSystemFileHandle 
        [fileHandle] = await window.showDirectoryPicker()

 if (fileHandle.kind === "file") {
 verifyPermission(fileHandle)
 // 运行针对文件的代码
        } else if (fileHandle.kind === "directory") {
 // 运行针对目录的代码
 verifyPermission(fileHandle)
        }
      }
 async function verifyPermission (fileHandle, withWrite) {
 const opts = {}
 if (withWrite) {
 opts.mode = "readwrite"
        }

 // 检查是否已经拥有相应权限,如果是,返回 true。
 if ((await fileHandle.queryPermission(opts)) === "granted") {
 return true
        }

 // 为文件请求权限,如果用户授予了权限,返回 true。
 if ((await fileHandle.requestPermission(opts)) === "granted") {
 return true
        }

 // 用户没有授权,返回 false。
 return false
      }

2.授权访问权限

3.得到FileSystemFileHandle

4.进行读写文件

FileSystemHandle - Web API 接口参考 | MDN

FileSystemFileHandle:createWritable() 方法 - Web API 接口参考 | MDN

Window:showDirectoryPicker() 方法 - Web API 接口参考 | MDN

相关推荐
烈风逍遥4 分钟前
第七篇:提示词模板管理与 Agent 提示词编排
前端·人工智能·后端
Amos_Web14 分钟前
Rspack 源码解析(十二):JavaScript Chunk 是如何被渲染出来的
前端·rust·源码
前端探险家Rick23 分钟前
React Native 二级弹出面板 + 键盘适配:从踩坑到正确方案
前端
用户9210802628627 分钟前
MCP 是什么?用 Figma MCP 辅助还原 Vue 页面
前端
用户9210802628627 分钟前
用 Figma MCP 还原 Vue 页面时,我遇到的三个问题
前端
修罗王28 分钟前
从 React Bits 到 Vue/Svelte Bits:重新定义前端“视觉表达层“
前端
kiros_wang29 分钟前
Notification 本地通知:定时消息、点击路由跳转、桌面角标适配
前端
flash俊杰36 分钟前
SQLite + sqlite-vec:100 篇文档内的私域知识库怎么做
前端
Hilaku1 小时前
为什么死磕 1px 的团队,用户体验反而更差?
前端·javascript·程序员