文件系统访问API:是否可以存储已保存或已加载文件的fileHandle以便以后使用? [英] File System Access API: is it possible to store the fileHandle of a saved or loaded file for later use?

查看:94
本文介绍了文件系统访问API:是否可以存储已保存或已加载文件的fileHandle以便以后使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在使用使用新的(ish)文件系统访问权限的应用API ,我想保存最近加载的文件的fileHandles,以显示最近的文件...".菜单选项,让用户无需打开系统文件选择窗口即可加载这些文件之一.

Working on an app that uses the new(ish) File System Access API, and I wanted to save the fileHandles of recently loaded files, to display a "Recent Files..." menu option and let a user load one of these files without opening the system file selection window.

本文有一段关于在indexedDB中存储fileHandles的段落,其中提到了返回的句柄来自API的消息是可序列化的",但是它没有任何示例代码,并且JSON.stringify不会这样做.

This article has a paragraph about storing fileHandles in IndexedDB and it mentions that the handles returned from the API are "serializable," but it doesn't have any example code, and JSON.stringify won't do it.

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

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可能会自动执行此操作,但这似乎也不起作用.

Is there a way to serialize the handle other than JSON? I thought maybe IndexedDB would do it automatically but that doesn't seem to work, either.

推荐答案

下面是一个最小的示例,演示了如何存储和检索文件句柄(

Here is a minimal example that demonstrates how to store and retrieve a file handle (a FileSystemHandle to be precise) in IndexedDB (the code uses the idb-keyval library for brevity):

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);
  }
});

我创建了一个演示,该演示显示了上面的代码.

I have created a demo that shows the above code in action.

这篇关于文件系统访问API:是否可以存储已保存或已加载文件的fileHandle以便以后使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆