← Back to Blog

Reading a Text File Using HTML and Javascript

html
javascript

By Kevin Hou

2 minute read

I just started working on a project that will analyze the user's text and look for patterns, word usage, etc. My first hurdle was creating a system in which the user can upload a text file and have the server read it as a string.

After a lot of piecing together research online, I think I've found the answer.

Start with a simple HTML form input. This form will accept a tag and, when submitted, will run the function "loadFile." I am using ReactJS so I had to bind the function to the parent.

1<form onSubmit={this.loadFile.bind(this)}> 2 Select text file: <input type="file" id="selectedFile" name="text" accept=".txt" /> 3 <input type="submit" /> 4</form> 5

In JSX, all elements must be explicitly closed. Void elements like <input> must either self-close with a slash or use a matching closing tag.

Now here's where the fun happens:

1loadFile: function() { 2 console.log("Loading file"); //Feedback 3 var selectedFile = document.getElementById('selectedFile').files[0]; //Identifying the selected file using the id of the form tag 4 console.log(selectedFile); //Feedback to make sure the file is loaded correctly 5 var reader = new FileReader(); //Create a document reader (built into HTML5) 6 reader.onload = function(e) { //Declare the asyncronous callback for when a file is loaded into the reader 7 var text = reader.result; //The contents of the text file 8 console.log(text); //Spits back the contents of the text file 9 } 10 reader.readAsText(selectedFile); //Calls the reader to read our selected text file 11 //The reader goes to its "onload" function and executes that code 12 return false; //Prevents the page from auto-refreshing 13} 14

That's it! It was so satisfying once it worked. Hope this helps!

Main Sources: