Browser-FS-Access
This module allows you to easily use the
File System Access API on supporting browsers,
with a transparent fallback to the <input type="file">
and <a download>
legacy methods.
This library is a ponyfill.
Read more on the background of this module in my post
Progressive Enhancement In the Age of Fugu APIs.
Live Demo
Try the library in your browser: https://googlechromelabs.github.io/browser-fs-access/demo/.
Installation
You can install the module with npm.
npm install --save browser-fs-access
Usage Examples
The module feature-detects support for the File System Access API and
only loads the actually relevant code.
Importing what you need
Import only the features that you need. In the code sample below, all
features are loaded. The imported methods will use the File System
Access API or a fallback implementation.
import {
fileOpen,
directoryOpen,
fileSave,
supported,
} from 'https://unpkg.com/browser-fs-access';
Feature detection
You can check supported
to see if the File System Access API is
supported.
if (supported) {
console.log('Using the File System Access API.');
} else {
console.log('Using the fallback implementation.');
}
Opening a file
const blob = await fileOpen({
mimeTypes: ['image/*'],
});
Opening multiple files
const blobs = await fileOpen({
mimeTypes: ['image/*'],
multiple: true,
});
Opening files of different MIME types
const blobs = await fileOpen([
{
description: 'Image files',
mimeTypes: ['image/jpg', 'image/png', 'image/gif', 'image/webp'],
extensions: ['.jpg', '.jpeg', '.png', '.gif', '.webp'],
multiple: true,
},
{
description: 'Text files',
mimeTypes: ['text/*'],
extensions: ['.txt'],
},
]);
Opening all files in a directory
Optionally, you can recursively include subdirectories.
const blobsInDirectory = await directoryOpen({
recursive: true,
});
Saving a file
await fileSave(blob, {
fileName: 'Untitled.png',
extensions: ['.png'],
});
Saving a Response
that will be streamed
const response = await fetch('foo.png');
await fileSave(response, {
fileName: 'foo.png',
extensions: ['.png'],
});
Saving a Promise<Blob>
that will be streamed.
No need to await
the Blob
to be created.
const blob = createBlobAsyncWhichMightTakeLonger(someData);
await fileSave(blob, {
fileName: 'Untitled.png',
extensions: ['.png'],
});
API Documentation
Opening files:
const options = {
mimeTypes: ['image/*'],
extensions: ['.png', '.jpg', '.jpeg', '.webp'],
multiple: true,
description: 'Image files',
startIn: 'downloads',
id: 'projects',
excludeAcceptAllOption: true,
};
const blobs = await fileOpen(options);
Opening directories:
const options = {
recursive: true,
mode:
startIn: 'downloads',
id: 'projects',
skipDirectory: (entry) => entry.name[0] === '.',
};
const blobs = await directoryOpen(options);
The module also polyfills a webkitRelativePath
property on returned files in a consistent way, regardless of the underlying implementation.
Saving files:
const options = {
fileName: 'Untitled.txt',
extensions: ['.txt'],
startIn: 'downloads',
id: 'projects',
excludeAcceptAllOption: true,
};
const existingHandle = previouslyOpenedBlob.handle;
const throwIfExistingHandleNotGood = true;
await fileSave(
blobOrResponseOrPromiseBlob,
options,
existingHandle,
throwIfExistingHandleNotGood
);
File operations and exceptions
The File System Access API supports exceptions, so apps can throw when problems occur (permissions
not granted, out of disk space,…), or when the user cancels the dialog. The legacy methods,
unfortunately, do not support exceptions (albeit there is an
HTML issue open for this request). If your app depends
on exceptions, see the file
index.d.ts
for the
documentation of the legacySetup
parameter.
Browser-FS-Access in Action
You can see the module in action in the Excalidraw drawing app.
It also powers the SVGcode app that converts raster images to SVGs.
Alternatives
A similar, but more extensive library called
native-file-system-adapter
is provided by @jimmywarting.
Ecosystem
If you are looking for a similar solution for dragging and dropping of files,
check out @placemarkio/flat-drop-files.
Acknowledgements
Thanks to @developit
for improving the dynamic module loading
and @dwelle for the helpful feedback,
issue reports, and the Windows build fix.
Directory operations were made consistent regarding webkitRelativePath
and parallelized and sped up significantly by
@RReverser.
The TypeScript type annotations were initially provided by
@nanaian.
Dealing correctly with cross-origin iframes was contributed by
@nikhilbghodke and
@kbariotis.
The exception handling of the legacy methods was contributed by
@jmrog.
The streams and blob saving was improved by @tmcw.
License and Note
Apache 2.0.
This is not an official Google product.