<!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
// 操作 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>
标签:function,文件,const,前端,await,return,操作,fileHandle
From: https://www.cnblogs.com/letgofishing/p/17457413.html