3 Ways To Load Files In HTML Javascript

Once upon a time, a student wanted to “link an HTML file picker to Javascript”… Master Coffee got confused for a while, but eventually figured out that the student meant “read a file”. Yes, that is possible in modern Javascript. Let us walk through some simple examples, let’s go!

 

CODE DOWNLOAD

I have released this under the MIT license, feel free to use it in your own project – Personal or commercial. Some form of credits will be nice though. 🙂

 

 

VIDEO TUTORIAL

 

 

METHOD 1) LOAD FROM FILE PICKER

1-picker.html
<!-- (PART A) FILE PICKER -->
<input type="file" id="picker" accept=".json" onchange="load()">
<script>
function load () {
  // (PART B) GET SELECTED FILE
  let file = document.getElementById("picker").files[0];

  // (PART C) READ SELECTED FILE
  let reader = new FileReader();
  reader.onload = () => {
    let data = JSON.parse(reader.result);
    console.log(data);
  };
  reader.readAsText(file);
}
</script>

This is one of the most common ways to load a file in Javascript.

  1. Create an HTML file picker first, you will want to restrict the file type with accept.
  2. On picking a file, we call load() and get the selected file.
  3. To read the selected file:
    • Create a reader = new FileReader() object.
    • Use the reader to read the selected file. In this example, we will read it as plain text – reader.readAsText().
    • Wait for the file to be fully loaded – reader.onload = DO SOMETHING.
    • We can then get the file contents with reader.result.

 

 

METHOD 2) LOAD SELECTED FOLDER

2-directory.html
<!-- (PART A) DIRECTORY PICKER -->
<input type="button" value="Open" onclick="load()">
<script>
function load() {
  // (PART B) SHOW DIRECTORY PICKER
  window.showDirectoryPicker()

  // (PART C) READ JSON FILES IN DIRECTORY
  .then(async handle => {
    for await (const entry of handle.values()) {
      if (entry.kind=="file" && entry.name.split(".").pop().toLowerCase()=="json") {
        let reader = new FileReader();
        reader.onload = () => {
          let data = JSON.parse(reader.result);
          console.log(entry.name, data);
        };
        reader.readAsText(await entry.getFile());
      }
    }
  })

  // (PART D) ON ERROR
  .catch(e => console.error(e));
}
</script>

To load multiple files, one way is to set <input type="file" multiple>. This is another way to do it, open a folder selector.

  1. Take note, this is just a regular button.
  2. On clicking the button, call window.showDirectoryPicker() to open the folder picker.
  3. When the user picks a folder.
    • Use for await (const entry of handle.values()) to loop through the contents of the selected folder.
    • entry.kind will indicate if it is a file or directory.
    • entry.name contains the file/folder name.
    • In this example, we are only interested in JSON files; Open and read the JSON file using the same file reader as in the previous example.
  4. That’s all. It is optional to handle the errors.

P.S. Take note that showDirectoryPicker() is experimental at the time of writing. It is supported in some browsers only, check the supported browsers here.

 

 

METHOD 3) LOAD FROM CACHE STORAGE

3-cache.html
(async () => {
  // (PART A) CREATE/OPEN CACHE
  let cache = await caches.open("demo");

  // (PART B) SAVE TO CACHE STORAGE
  await cache.put("dummy.json", await fetch("dummy.json"));

  // (PART C) RETRIEVE & DELETE CACHED FILE
  let data = await (await caches.match("dummy.json")).json();
  console.log(data);
  cache.delete("dummy.json");
})();

Lastly, this is not exactly “opening a file”. But both previous examples require the user’s permission, and this one is “silent”. Long story short, cache storage is a “sandbox folder” for keeping web app assets, and we can use it to save/load files too.

  1. Use caches.open("NAME") to create/open a cache first.
  2. Then, fetch the file you want to “save” and put it into the cache – cache.put("FILE.NAME", await fetch("URL OR OBJECT URL"))
  3. Lastly, retrieve the file with cache.match("FILE.NAME").

 

 

THE END – HOW TO SAVE?

That’s all for this short tutorial and sharing. If you want to save files in Javascript – Check out my other tutorial on the ways to store data in Javascript, or how to save files in Javascript.

 

CHEAT SHEET

Ways To Load Files in HTML Javascript (click to enlarge)