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

2

8

Can I use the File System Access API (https://web.dev/file-system-access/) to create something like a file explorer within a website (react).

I plan to make a simple online file explorer that lets you browse open a folder and then lets you browse through the folder, play videos and MP3s.

(I know this wasn't possible a few years ago, because it was impossible for js to access anything in the local storage, I just wanted to know if anything have changed or not. If File System Access API is not the way to go, can you suggest some better way to read bulk local files from a folder.)

Patterman answered 4/2, 2021 at 6:22 Comment(2)
Yes the file system API is the way to go, and yes you can do it, in Chrome, from a securecontext.Opia
There's a web component using this api - github.com/DannyMoerkerke/file-tree which is used at whatpwacando.today/file-systemGoldbrick
P
4

For future reference, I'm posting my work; https://github.com/akshayknz/filesystem-access-api/blob/main/file.html (A html page which displays all images from picked folder.)

Note:The API only work in secure contexts (i.e. it works in https:// and file:///)

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

or

const dirHandle = await window.showDirectoryPicker();
const fileHandle = await dirHandle.getFileHandle(entry.name, {});
const file = await fileHandle.getFile();
Patterman answered 24/2, 2021 at 5:58 Comment(0)
F
6

This is possible with the File System Access API today:

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

You can explore the folder structure by going deeper if entry.kind is a directory.

Frissell answered 23/2, 2021 at 15:8 Comment(3)
Thank you. And [fileHandle] = await window.showOpenFilePicker();Patterman
hi how do I get the list without using the await keyword?Congruity
It’s an asynchronous API designed to be non-blocking. You have to await its result, there’s no way around this. You can of course use showOpenFilePicker.then((handles) => {/*…*/}) as ana alternative code style if you prefer.Frissell
P
4

For future reference, I'm posting my work; https://github.com/akshayknz/filesystem-access-api/blob/main/file.html (A html page which displays all images from picked folder.)

Note:The API only work in secure contexts (i.e. it works in https:// and file:///)

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

or

const dirHandle = await window.showDirectoryPicker();
const fileHandle = await dirHandle.getFileHandle(entry.name, {});
const file = await fileHandle.getFile();
Patterman answered 24/2, 2021 at 5:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.