如何打开目录

Thomas Steiner
Thomas Steiner

处理目录并不是您每天都要处理的内容,但偶尔也会出现用例,例如需要处理目录中的所有图片。借助 File System Access API,用户现在可以在浏览器中打开目录,并决定是否需要写入权限。

如需打开目录,请调用 showDirectoryPicker(),这将返回一个包含所选目录的 promise。如果您需要写入权限,可以将 { mode: 'readwrite' } 传递给该方法。

浏览器支持

  • 86
  • 86
  • x
  • x

来源

经典路线

使用 <input type="file" webkitdirectory> 元素

网页上的 <input type="file" webkitdirectory> 元素允许用户点击该元素并打开目录。现在,诀窍在于使用 JavaScript 以隐形的方式将元素插入网页,然后以程序化方式点击它。

浏览器支持

  • 7
  • 13
  • 50
  • 11.1

来源

渐进式增强

下面的方法会在支持 File System Access API 的情况下使用,否则会回退到传统方法。在这两种情况下,函数都会返回一个目录,但在支持 File System Access API 的情况下,每个文件对象还会有一个存储在 directoryHandle 属性中的 FileSystemDirectoryHandle 和一个存储在 handle 属性中的 FileSystemFileHandle,因此您可以选择将句柄序列化到磁盘。

const openDirectory = async (mode = "read") => {
 
// Feature detection. The API needs to be supported
 
// and the app not run in an iframe.
 
const supportsFileSystemAccess =
   
"showDirectoryPicker" in window &&
   
(() => {
     
try {
       
return window.self === window.top;
     
} catch {
       
return false;
     
}
   
})();
 
// If the File System Access API is supported…
 
if (supportsFileSystemAccess) {
    let directoryStructure
= undefined;

   
// Recursive function that walks the directory structure.
   
const getFiles = async (dirHandle, path = dirHandle.name) => {
     
const dirs = [];
     
const files = [];
     
for await (const entry of dirHandle.values()) {
       
const nestedPath = `${path}/${entry.name}`;
       
if (entry.kind === "file") {
          files
.push(
            entry
.getFile().then((file) => {
              file
.directoryHandle = dirHandle;
              file
.handle = entry;
             
return Object.defineProperty(file, "webkitRelativePath", {
                configurable
: true,
                enumerable
: true,
               
get: () => nestedPath,
             
});
           
})
         
);
       
} else if (entry.kind === "directory") {
          dirs
.push(getFiles(entry, nestedPath));
       
}
     
}
     
return [
       
...(await Promise.all(dirs)).flat(),
       
...(await Promise.all(files)),
     
];
   
};

   
try {
     
// Open the directory.
     
const handle = await showDirectoryPicker({
        mode
,
     
});
     
// Get the directory structure.
      directoryStructure
= getFiles(handle, undefined);
   
} catch (err) {
     
if (err.name !== "AbortError") {
        console
.error(err.name, err.message);
     
}
   
}
   
return directoryStructure;
 
}
 
// Fallback if the File System Access API is not supported.
 
return new Promise((resolve) => {
   
const input = document.createElement('input');
    input
.type = 'file';
    input
.webkitdirectory = true;

    input
.addEventListener('change', () => {
      let files
= Array.from(input.files);
      resolve
(files);
   
});
   
if ('showPicker' in HTMLInputElement.prototype) {
      input
.showPicker();
   
} else {
      input
.click();
   
}
 
});
};

深入阅读

演示

<!DOCTYPE html>
<html lang="en">
 
<head>
   
<meta charset="utf-8" />
   
<meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="icon"
      href="data:image/svg+xml,
<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📂</text></svg>"
    />
   
<title>How to open a directory</title>
 
</head>
 
<body>
   
<h1>How to open a directory</h1>
   
<button type="button">Open directory</button>
   
<pre></pre>
 
</body>
</html>

       
:root {
 
color-scheme: dark light;
}

html
{
 
box-sizing: border-box;
}

*,
*:before,
*:after {
 
box-sizing: inherit;
}

body
{
 
margin: 1rem;
 
font-family: system-ui, sans-serif;
}
       

       
const button = document.querySelector('button');
const pre = document.querySelector('pre');

const openDirectory = async (mode = "read") => {
 
// Feature detection. The API needs to be supported
 
// and the app not run in an iframe.
 
const supportsFileSystemAccess =
   
"showDirectoryPicker" in window &&
   
(() => {
     
try {
       
return window.self === window.top;
     
} catch {
       
return false;
     
}
   
})();
 
// If the File System Access API is supported…
 
if (supportsFileSystemAccess) {
    let directoryStructure
= undefined;

   
const getFiles = async (dirHandle, path = dirHandle.name) => {
     
const dirs = [];
     
const files = [];
     
for await (const entry of dirHandle.values()) {
       
const nestedPath = `${path}/${entry.name}`;
       
if (entry.kind === "file") {
          files
.push(
            entry
.getFile().then((file) => {
              file
.directoryHandle = dirHandle;
              file
.handle = entry;
             
return Object.defineProperty(file, "webkitRelativePath", {
                configurable
: true,
                enumerable
: true,
               
get: () => nestedPath,
             
});
           
})
         
);
       
} else if (entry.kind === "directory") {
          dirs
.push(getFiles(entry, nestedPath));
       
}
     
}
     
return [
       
...(await Promise.all(dirs)).flat(),
       
...(await Promise.all(files)),
     
];
   
};

   
try {
     
const handle = await showDirectoryPicker({
        mode
,
     
});
      directoryStructure
= getFiles(handle, undefined);
   
} catch (err) {
     
if (err.name !== "AbortError") {
        console
.error(err.name, err.message);
     
}
   
}
   
return directoryStructure;
 
}
 
// Fallback if the File System Access API is not supported.
 
return new Promise((resolve) => {
   
const input = document.createElement('input');
    input
.type = 'file';
    input
.webkitdirectory = true;

    input
.addEventListener('change', () => {
      let files
= Array.from(input.files);
      resolve
(files);
   
});
   
if ('showPicker' in HTMLInputElement.prototype) {
      input
.showPicker();
   
} else {
      input
.click();
   
}
 
});
};

button
.addEventListener('click', async () => {
 
const filesInDirectory = await openDirectory();
 
if (!filesInDirectory) {
   
return;
 
}
 
Array.from(filesInDirectory).forEach((file) => (pre.textContent += `${file.name}\n`));
});