首页 > 解决方案 > 文件系统访问 API:是否可以存储已保存或已加载文件的文件句柄以供以后使用?

问题描述

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

这篇文章有一段关于在 IndexedDB 中存储文件句柄,它提到从 API 返回的句柄是“可序列化的”,但它没有任何示例代码,JSON.stringify 不会这样做。

文件句柄是可序列化的,这意味着您可以将文件句柄保存到 IndexedDB,或调用 postMessage() 在同一顶级源之间发送它们。

除了 JSON 之外,还有其他方法可以序列化句柄吗?我想也许 IndexedDB 会自动完成,但这似乎也不起作用。

标签: javascriptserializationindexeddb

解决方案


这是一个最小示例,演示如何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);
  }
});

我创建了一个演示,展示了上面的代码。


推荐阅读