文件系统访问API:是否可以存储已保存或已加载文件的fileHandle以供以后使用?

在使用新的(ish)文件系统访问 API的应用程序上工作,我想保存最近加载的文件的文件句柄,以显示“最近的文件...”菜单选项并让用户加载这些文件之一而不打开系统文件选择窗口。

这篇文章有一段关于在IndexedDB中存储fileHandles,它提到从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);
  }
});

我已经创建了一个演示,显示了上面的代码。


以上是文件系统访问API:是否可以存储已保存或已加载文件的fileHandle以供以后使用?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>