Categories
JavaScript Answers

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

Spread the love

Sometimes, 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 add a file input and then read the select files from the input’s value.

For instance, we write

const file = document.getElementById("fileForUpload").files[0];
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 first selected file with files[0].

Then we create a FileReader object.

And then we call readAsText to read the file as text.

Then result is available in the reader.onload method.

We get the file’s text from evt.target.result.

Conclusion

To read file contents on the client-side in JavaScript in various browsers, we add a file input and then read the select files from the input’s value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *