FileReader() in javascript. What is it, and how does it work?
h
Baconman321 (539)

FileReader() in javascript. What is it, and how does it work?

We all know the benefits of backend, you get to handle files, connect to databases, and process sensitive information. However, javascript is catching up. Nowadays you can a lot of stuff on client side that you can do on backend. Of course, sensitive information handling is still a nono for javascript (probably will always be), but other than that, we can do a lot of stuff that backend can do. One of those things is file reading.


While you can't write to files or or store files with javascript, you can read files. In this tutorial, I will cover the FileReader() object in javascript, as well as two methods of reading a file it has. I assume that you have basic knowledge of javascript and html, as well as basic knowledge of file handling and blobs. Let's get started, shall we?


Ok, the first thing we will do is review the FileReader() object in javascript. What is it? What does it do? This is pretty self explanatory: it reads files.
According to javascript.info, the filereader object is "an object with the sole purpose of reading data from Blob (and hence File too) objects." So, what does that mean? It means it is meant to read files and blobs (a Binary Large OBject. wikipedia article). This is handy if you are going to ask a user to submit a file for you to use. How to set it up? Easy. In html, you would have an input with a type of file like so:

<input type="file" id="fileInput"/>

Note, if you want to add more than one file, you add a multiple="multiple" attribute to the input tag.
Now, in javascript. I'll break this down too.

document.getElementById("fileInput").addEventListener("change",function(){
   let file = document.getElementById("fileInput").files[0];
   let reader = new FileReader();
   reader.onload = function(){
      let result = reader.result;
   }
   reader.onerror = function(){
      let err = reader.error;
   }
});

Kind of confusing, isn't it? Don't worry. I'll explain.
The first thing that pops up is an event listener. This listens for when someone adds a file (actually, it listens for a change of files, but unless someone selects the same file it will fire). Inside this, we add a function. In that function, we declare a file variable.

let file = document.getElementById("fileInput").files[0];

Hmmm, I bet you see that [0] at the end right? Yep, it means that the input.files attribute for the input returns an array like object. For simplicity here, I only select the first one. Remember you can add more than one files? If you want to get all of them and do something with each, you'll have to iterate over them. I assume you already know how to do that, so let's get the next couple lines of code.
The next line of code is

let reader = new FileReader();

This creates our FileReader() object. After that, we listen for when the file reader is done loading. It may take some time, since it's reading from the disk drive of the user's computer.

reader.onload = function(){
   let result = reader.result;
}

reader.result is the result of the file reader reading the file. Depending on the method you use, this could be the text of the file, a blob, or an array buffer. I will only cover the text and blob methods of reading a file.
The next couple lines of code listens for an error.

reader.onerror = function(){
   let err = reader.error;
}

reader.error is the error returned if there is one.
There we go! We have reviewed the entire file reader method right? Not quite. I left out the part that will vary depending on what you want it to do: the actual reading of the file. There are three different methods of doing this:

readAsArrayBuffer(blob)
readAsText(blob, [encoding])
readAsDataURL(blob)

readAsArrayBuffer() returns an array buffer.
readAsText() returns a stringified text of the file (basically it's raw content).
readAsDataURL() returns a base64 data URL
I will only cover readAsText() and readAsDataURL(). readAsArrayBuffer() uses the same setup as the other methods, but it just returns a different result.
To read the file as text, add below the error handling code:

reader.readAsText(file);

To read as a data URL, replace the above code with this:

reader.readAsDataURL(file);

As you can see, this takes the file variable we declared earlier as input. readAsArrayBuffer() does the same thing, but just returns a different result. Ok, now for an example. What to do with our result?

Example 1:

Let's log our result to the console. Note that this is not really a good idea in practice, especially if a file is large. Add this to the reader.onload function (make sure you have reader.readAsDataURL(file) added to the bottom of the onchange function):

console.log(result);

This logs the stringified content of our file to the console. Things you can do with this:

  • Read a text file that contains a story and upload it to a story sharing site
  • Read a file then send it to backend to manipulate it if you are making a file converter/editor.
    These are just examples, the possibilities are very broad. Try it out yourself!

Example 2:

Let's make an audio file and set the source to the file result we just read. Note that this is assuming the user uploaded a file that is an audio. You can actually check it's type, but I'm not going to get into that. It is also extremely processing power consuming since it is reading a large encoded audio file as it's source. Since we are using the readAsDataURL() method, it is a valid url, containing a blob as a url. To do this, just add to your reader.onload function (make sure you have reader.readAsDataURL(file) added to the bottom of the onchange function):

let audio = new Audio();
audio.src = reader.result;
audio.play();

Assuming that the file is a valid audio file, this should work. Again, this is just an example. The possibilities are very broad.

Challenge:

Now, I have a challenge for you. Try making a website that prompts a user to upload image files and post them on the website. This doesn't have to be fancy, and you don't have to store it. Just a challenge. Let me know your results.

Conclusion:

FileReader is a very powerful object in javascript, allowing the user to submit files to your website and have you handle them. This is used everywhere, from the file converters, to websites like facebook, tiktok, instagram, and such, to even the website I made this tutorial on. I hope you guys found this tutorial useful, it's my first. Leave a comment letting me know what you think. Bacon boi out!
Sources used:

You are viewing a single comment. View All