About
The file api 1) is a browser javascript api that allows file system operation in the browser.
With the FileApi, you can't open and edit and save the same file.
The original file when saved (download) will end up as a new copy of the original file in the operating system's default Downloads folder.
Operation
Opening / Uploading a file
Uploading a file:
- You can open and read files via the input of type file
<input type="file" accept=".txt"/>
document.querySelector("input").addEventListener('change', async (event) => {
let file = event.target.files[0];
console.log(`File name: ${file.name}`);
let text = await (new Response(file)).text();
console.log(text);
});
- Result: Choose a text file, the file name and content will be printed below
Opening / Uploading a list of files in a directory
By adding the boolean attribute webkitdirectory 3), you can open folders (ie directories) and upload a list of files.
- The HTML
<input type="file" webkitdirectory />
- With the change event, you can retrieve all files in the chosen directory
document.querySelector("input").addEventListener('change', (event) => {
let files = event.target.files;
for (let i=0; i<files.length; i++) {
console.log(files[i].webkitRelativePath);
};
});
Note that after choosing your directory, you will get the following warning dialog
- Result: Choose a directory, we will list the name of their descendant files below.
Despite its vendor-prefixed name, webkitdirectory is supported in all browser. 4)
Downloading / Saving a file
Example on how to download a file
Saving a file with the FileApi is limited to downloading a file. It works thanks to the anchor download attribute.
<a id="download" download="foobar.txt">Click to Save / Download the file</a>
let a = document.querySelector("#download");
let blob = new Blob(["foobar"], {type: 'text/plain'});
a.href = URL.createObjectURL(blob);
- To prevent memory leaks, we revoke the URL after the download (ie close the resource) with a click callback
a.addEventListener('click', (e) => {
// To prevent memory leaks, always revoke the URL after the download.
setTimeout(() => URL.revokeObjectURL(e.target.href), 30 * 1000);
});
- Result:
Features
File API interface:
- Blob - a data container
- File - a blob with file system features
- FileList5) - an object that represents a list of file created by the html input file
- Blob.close()
- Blob.type
- The concept of read errors