File System Access API example
File System Access API example. showOpenFilePicker() returns a handle. Read and write the real file. Not an upload.
The problem
<input type="file"> gives you a snapshot. You cannot write it back. The page never held a
path, only a copy in memory.
The method
showOpenFilePicker() returns a FileSystemFileHandle. getFile() reads.
createWritable() writes the same file. showSaveFilePicker() mints a new handle.
showDirectoryPicker() is the folder.
What to do
- Run
showOpenFilePicker(). Pick a text file. - Run
getFile(). Edit in the stage. - Run
createWritable()to write back, orshowSaveFilePicker()for a new file.
showOpenFilePicker()
A user gesture. You get a handle, not the bytes. Cancel throws AbortError.
const [handle] = await showOpenFilePicker({
multiple: false,
types: [{ description: "Text", accept: { "text/*": [".txt", ".md"] } }],
})
getFile()
The handle yields a File. Text lands in the stage. Images preview. This lab does not write pixels
back.
const file = await handle.getFile()
const text = await file.text()
queryPermission()
Handles remember permission. queryPermission({ mode: "readwrite" }) is granted, denied, or prompt.
Request asks again.
const state = await handle.queryPermission({ mode: "readwrite" })
await handle.requestPermission({ mode: "readwrite" })
createWritable()
Opens a FileSystemWritableFileStream on the same handle. write() then
close(). That is save. Images stay read-only here.
const writable = await handle.createWritable()
await writable.write(text)
await writable.close()
showSaveFilePicker()
A new handle. The page can create a file that did not exist. The editor contents go there.
const handle = await showSaveFilePicker({
suggestedName: "untitled.txt",
})
const writable = await handle.createWritable()
await writable.write(text)
await writable.close()
showDirectoryPicker()
A folder handle. entries() is an async iterator of names and child handles. This lab lists them. It
does not walk the tree.
const dir = await showDirectoryPicker()
for await (const [name, child] of dir.entries()) {
child.kind
}