在使用新的(ish)File System Access API 的应用程序上工作,我想保存最近加载的文件的文件句柄,以显示“最近的文件...”菜单选项,让用户在不打开系统文件选择窗口的情况下加载其中一个文件。
This article有一段关于在 IndexedDB 中存储 fileHandles 并提到从 API 返回的句柄是“可序列化的”,但它没有任何示例代码,并且 JSON.stringify 不会这样做。
File handles are serializable, which means that you can save a file handle to IndexedDB, or call postMessage() to send them between the same top-level origin.
除了 JSON 之外,还有其他方法可以序列化句柄吗?我想也许 IndexedDB 会自动完成,但这似乎也不起作用。
最佳答案
下面是一个演示如何在 IndexedDB 中存储和检索文件句柄(准确地说是 FileSystemHandle
)的最小示例(代码使用 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);
}
});
我创建了一个 demo这显示了上面的代码。
关于javascript - 文件系统访问 API : is it possible to store the fileHandle of a saved or loaded file for later use?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65928613/