<!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"] },
},
],
};
_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,
};
const [fileHandle] = await window.showOpenFilePicker(pickerOpts);
console.log('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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】