How to read file contents on the client-side in JavaScript in various browsers?

Spread the love

Somewtimes, we want to read file contents on the client-side in JavaScript in various browsers.

In this article, we’ll look at how to read file contents on the client-side in JavaScript in various browsers.

How to read file contents on the client-side in JavaScript in various browsers?

To read file contents on the client-side in JavaScript in various browsers, we use the FileReader constructor.

For instance, we write

const [file] = document.getElementById("fileForUpload").files;
if (file) {
  const reader = new FileReader();
  reader.readAsText(file, "UTF-8");
  reader.onload = (evt) => {
    document.getElementById("fileContents").innerHTML = evt.target.result;
  };
  reader.onerror = (evt) => {
    document.getElementById("fileContents").innerHTML = "error reading file";
  };
}

to select the file input with getElementById.

We get the files selected with files.

Then we get the first one with destructuring.

Next, we create a FileReader object.

Then we call readAsText to read the file as text.

Finally, we get the value from the onload method.

evt.target.result has the read file contents.

Conclusion

To read file contents on the client-side in JavaScript in various browsers, we use the FileReader constructor.

Leave a Reply

Your email address will not be published.