javascript - 文件系统访问 API:是否可以存储已保存或已加载文件的文件句柄以供以后使用?
问题描述
在使用新的(ish)文件系统访问 API的应用程序上工作,我想保存最近加载的文件的文件句柄,以显示“最近的文件...”菜单选项并让用户加载其中一个文件而不打开系统文件选择窗口。
这篇文章有一段关于在 IndexedDB 中存储文件句柄,它提到从 API 返回的句柄是“可序列化的”,但它没有任何示例代码,JSON.stringify 不会这样做。
文件句柄是可序列化的,这意味着您可以将文件句柄保存到 IndexedDB,或调用 postMessage() 在同一顶级源之间发送它们。
除了 JSON 之外,还有其他方法可以序列化句柄吗?我想也许 IndexedDB 会自动完成,但这似乎也不起作用。
解决方案
这是一个最小示例,演示如何FileSystemHandle
在 IndexedDB 中存储和检索文件句柄(准确地说是 a)(代码使用idb-keyval库为简洁起见):
import { get, set } from 'https://unpkg.com/idb-keyval@5.0.2/dist/esm/index.js';
const pre = document.querySelector('pre');
const button = document.querySelector('button');
button.addEventListener('click', async () => {
try {
const fileHandleOrUndefined = await get('file');
if (fileHandleOrUndefined) {
pre.textContent =
`Retrieved file handle "${fileHandleOrUndefined.name}" from IndexedDB.`;
return;
}
// This always returns an array, but we just need the first entry.
const [fileHandle] = await window.showOpenFilePicker();
await set('file', fileHandle);
pre.textContent =
`Stored file handle for "${fileHandle.name}" in IndexedDB.`;
} catch (error) {
alert(error.name, error.message);
}
});
我创建了一个演示,展示了上面的代码。
推荐阅读
- html - 试图通过 background-image:url(...) 在同样是 background-image:url(...) 的图像上叠加图像 - 不起作用
- html - onChange 文本框值未使用 React 以 HTML 形式更新
- asp.net-core - 从 AJAX 生成时提交按钮不起作用
- multithreading - 如果程序创建了太多线程会发生什么?
- google-bigquery - 如何解决无法确定项目描述的biquery cli ls操作错误
- javascript - 通过 jQuery Ajax 调用 django 视图函数
- bash - .bash_profile - 如何修复意外的 EOF 错误
- c# - 我希望我的自动移动汽车受到重力的影响
- discord.js - 如何从 Discord 机器人中删除 ping 命令
- android - ANativeWindow_getHeight 有时会减去导航栏高度