Categories
JavaScript Answers

How to read uploaded text file contents in HTML with JavaScript?

Spread the love

Sometimes, we want to read uploaded text file contents in HTML with JavaScript.

In this article, we’ll look at how to read uploaded text file contents in HTML with JavaScript.

How to read uploaded text file contents in HTML with JavaScript?

To read uploaded text file contents in HTML with JavaScript, we use file reader.

For instance, we write

const reader = new FileReader();
reader.onload = (event) => console.log(event.target.result);
reader.onerror = (error) => console.error(error);
reader.readAsText(file);

to create a FileReader object.

And then we set the onload and onerror event handlers.

We get the read file from event.target.result.

Then we call readAsText to read the file into a string.

Conclusion

To read uploaded text file contents in HTML with JavaScript, we use file reader.

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 *