DEV Community

Digamber Singh
Digamber Singh

Posted on

Read Local Text File using JavaScript FileReader API

HTML5 FileReader API

In this small tutorial, I am going to share with you how you can upload a .txt file and read its content using HTML5 file API from the client side.

HTML
Create an index.html file and add file input attribute in it. Within the index.html file declare the file input tag along with onchange event listener. This event listener will trigger the showFile() function when the user selects a .txt file.

JavaScript

In js file we will be writing logic for uploading a text file.

1 - Check whether your browser supports HTML5 File API

2 - Declare showFile() function
3 - Create file reference variable to uploaded text file
4 - Create preview reference to HTML div where to show text
5 - Create reference to reader = new FileReader() API
6 - Declare a textFile variable to apply text file validation
7 - Declare reader.onload method, within the onload function declare preview.innerHTML reference variable where you'll be showing uploaded text file.
8 - Call reader.readAsText(file) method and pass file variable outside the reader.onload method

This is just a small topic about HTML5 FileReader API to read a text file, here is the detailed article to Get Started with HTML5 FileReader API to Upload Images and Text Files

Top comments (1)

Collapse
 
bektemir1 profile image
Benjamin :)

the end