纯前端操作文件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .panel {
            width: 300px;
            height: 200px;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <textarea class="panel"></textarea>
    <div>
        <button onclick="createFile()">创建文件</button>
        <button onclick="openFile()">选择文件</button>
        <button onclick="saveFile()">保存文件</button>
        <button onclick="saveAsFile()">另存文件</button>
    </div>
</body>
<script>
    let _fileHandle
    function getDom() {
        return document.querySelector(".panel")
    }
    function getVal() {
        const dom = getDom()
        return dom.value
    }
    function setVal(val) {
        const dom = getDom()
        dom.innerText = val
    }
    // 创建文件
    async function createFile() {
        const opts = {
            types: [
                {
                    description: "Text file",
                    accept: { "text/plain": [".txt"] },
                },
            ],
        };
        // 保存文件api则直接返回了 FileSystemFileHandle
        _fileHandle = await window.showSaveFilePicker(opts);
        return _fileHandle
    }
    // 打开文件
    async function openFile() {
        const pickerOpts = {
            types: [
                {
                    description: "Images",
                    accept: {
                        "image/*": [".png", ".gif", ".jpeg", ".jpg", ".txt"],
                    },
                },
            ],
            excludeAcceptAllOption: true,
            multiple: false,
        };
        // 打开文件选择器,解构返回的数组中的第一个元素,该api返回的是一个数组,数组第一个元素是 FileSystemFileHandle
        const [fileHandle] = await window.showOpenFilePicker(pickerOpts);
        console.log('fileHandle:', fileHandle);
        _fileHandle = fileHandle
        // 操作 fileHandle 的后续代码
        const file = await fileHandle.getFile()
        setVal(await file.text())
        return fileHandle
    }
    // 保存文件
    async function saveFile() {
        const fileHandle = _fileHandle ? _fileHandle : await createFile()
        save(fileHandle)
    }
    async function save(handle) {
        if (!handle) return
        const writable = await handle.createWritable();
        await writable.write(getVal());
        await writable.close();
    }
    async function saveAsFile() {
        const fileHandle = await createFile()
        save(fileHandle)
    }
</script>

</html>
posted @ 2023-06-05 11:41  走我们钓鱼去  阅读(24)  评论(0编辑  收藏  举报