页面访问文件及文件夹

887 阅读2分钟

之前大部份文件夹和文件都是通过后端程序,进行编辑更新操作。虽然node.js也可以对文件系统编辑,但是它仍然属于后端程序。有没有在前端就可以对文件系统编辑呢,那是有的。File System Access API就是javaScript可以通过用户授权来访问本地文件系统

1、File System Access API

File System Access API使得JavaScript可以读写用户选择的本地文件,提供了更好的用户体验和更多的功能。 注意的是,这些API需要在安全上下文中运行,也就是必须使用HTTPS协议或localhost来访问页面。而且这个API也不是所有浏览器都支持,需要检查浏览器是否支持这个API,目前谷歌浏览器是支持的。

  • window.showOpenFilePicker():打开一个文件选择器,让用户选择一个或多个文件。
async function pickFile() {
  const [fileHandle] = await window.showOpenFilePicker();
  const file = await fileHandle.getFile();
  console.log(file.name);
}
document.querySelector("body").addEventListener("click", pickFile);
//打开一个文件选择器,选择一个文件。选择后,它会打印文件名

  • window.showSaveFilePicker():打开一个文件保存器,让用户选择一个位置来保存文件。
async function saveFile() {
  const fileHandle = await window.showSaveFilePicker();
  const writable = await fileHandle.createWritable();
  await writable.write('Hello, world!');
  await writable.close();
}
document.querySelector("body").addEventListener("click", saveFile);
//打开一个文件保存器,选择一个位置来保存文件。选择后,它会将 "Hello, world!" 写入该文件

  • window.showDirectoryPicker():打开一个目录选择器,让用户选择一个目录。
    async function pickDirectory() {
        const dirHandle = await window.showDirectoryPicker();
        const entries = await dirHandle.entries();
        for await (const [type,file] of entries) {
            console.log(file.name);
        }
    }
document.querySelector("body").addEventListener("click", pickDirectory);
//会打开一个目录选择器,选择一个目录。选择后,它会打印该目录下的文件和文件夹名

  • FileSystemHandle.getFile():返回一个 File 对象,表示选择的文件。

  • FileSystemHandle.createWritable():返回一个可写入WritableStream 对象,用于向选择的文件写入数据。

2、例子

选择一个文件,将文件内容读取到一个文本框中,并显示一个保存按钮。当用户修改文本框中的内容并点击保存按钮时,会将修改后的内容写回到选择的文件中

<body>
    <div style="width:100px;height:100px;background: blue;">

    </div>
</body>
<script>
    async function pickFile() {
        const [fileHandle] = await window.showOpenFilePicker();
        const file = await fileHandle.getFile();
        const contents = await file.text();
        const textarea = document.createElement('textarea');
        textarea.value = contents;
        document.body.appendChild(textarea);
        const button = document.createElement('button');
        button.textContent = 'Save';
        button.onclick = async () => {
            const writable = await fileHandle.createWritable();
            await writable.write(textarea.value);
            await writable.close();
        };
        document.body.appendChild(button);
    }
    document.querySelector("body>div").addEventListener("click", pickFile)
</script>

3、参考

chrome file system access

use file system access api to handle local files

不使用file类型input也能触发文件上传