Table of Contents

How to handle files in Javascript with the File API of the Browser?

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:

<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);
});

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.

<input type="file" webkitdirectory  />
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

Html Input File Multiple Warning Dialog

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);
 
a.addEventListener('click', (e) => {
    // To prevent memory leaks, always revoke the URL after the download.
    setTimeout(() => URL.revokeObjectURL(e.target.href), 30 * 1000);
});

Features

File API interface:

Documentation / Reference