FileSystemHandle
Baseline 广泛可用 *
注意:此功能在 Web Workers 中可用。
FileSystemHandle 接口是 File System API 的一部分,它表示一个文件或目录条目。多个句柄可以指向同一个条目。在大多数情况下,您不会直接使用 FileSystemHandle,而是使用它的子接口 FileSystemFileHandle 和 FileSystemDirectoryHandle。
基于 FileSystemHandle 的接口
以下是基于 FileSystemHandle 接口的接口列表。
FileSystemFileHandle-
表示一个文件条目的句柄。
FileSystemDirectoryHandle-
提供一个目录条目的句柄。
实例属性
实例方法
isSameEntry()-
比较两个句柄,判断它们所关联的条目(文件或目录)是否匹配。
queryPermission()实验性-
查询当前句柄的当前权限状态。
remove()实验性 非标准-
请求从底层文件系统中移除句柄所代表的条目。
requestPermission()实验性-
请求文件句柄的读权限或读写权限。
示例
类型检查
下面的代码允许用户从文件选择器中选择一个文件,然后检查返回的句柄是文件还是目录。
js
// store a reference to our file handle
let fileHandle;
async function getFile() {
// open file picker
[fileHandle] = await window.showOpenFilePicker();
if (fileHandle.kind === "file") {
// run file code
} else if (fileHandle.kind === "directory") {
// run directory code
}
}
查询/请求权限
以下异步函数将在用户已授予文件句柄读或读写权限时返回 true。如果尚未授予权限,则会请求权限。
js
// fileHandle is a FileSystemFileHandle
// withWrite is a boolean set to true if write
async function verifyPermission(fileHandle, withWrite) {
const opts = {};
if (withWrite) {
opts.mode = "readwrite";
}
// Check if we already have permission, if so, return true.
if ((await fileHandle.queryPermission(opts)) === "granted") {
return true;
}
// Request permission to the file, if the user grants permission, return true.
if ((await fileHandle.requestPermission(opts)) === "granted") {
return true;
}
// The user did not grant permission, return false.
return false;
}
比较条目
以下函数将单个条目与条目数组进行比较,并返回一个新数组,其中移除了任何匹配的条目。
js
function removeMatches(fileEntry, entriesArr) {
const newArr = entriesArr.filter((entry) => !fileEntry.isSameEntry(entry));
return newArr;
}
规范
| 规范 |
|---|
| 文件系统 # api-filesystemhandle |
浏览器兼容性
加载中…