访问给定文件夹中的所有文件(文件系统访问 API)

Access all files within a given folder (The File System Access API)

我可以使用 文件系统访问 API (https://web.dev/file-system-access/) 在网站中创建类似文件浏览器的东西吗(反应)。

我打算制作一个简单的在线文件资源管理器,让您浏览打开文件夹,然后浏览文件夹、播放视频和 MP3。

(我知道这在几年前是不可能的,因为js不可能访问本地存储中的任何东西,我只是想知道是否有任何改变。如果文件系统访问API 不是要走的路,你能建议一些更好的方法来从文件夹中读取批量本地文件。)

今天使用文件系统访问 API 可以做到这一点:

const dirHandle = await window.showDirectoryPicker();
for await (const entry of dirHandle.values()) {
  console.log(entry.kind, entry.name);
}

如果 entry.kind 是一个目录,您可以更深入地探索文件夹结构。

为了将来参考,我发布了我的作品; https://github.com/akshayknz/filesystem-access-api/blob/main/file.html(显示所选文件夹中所有图像的 html 页面。)

注意:API 仅在安全上下文中有效(即它在 https:// 和 file:/// 中有效)

[fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const contents = await file.text();

const dirHandle = await window.showDirectoryPicker();
const fileHandle = await dirHandle.getFileHandle(entry.name, {});
const file = await fileHandle.getFile();