In case of image upload, we always have to show the image preview before proceeding with the upload process. Similarly, in case of text file upload, we have to show the contents of the text file in a text box.
Please check out online base64 to image converter tool to see it in action. To read text files, we can make use of the readAsText() method.
In the following example, we have an input field of type file and a text box. We will select a text file and display its content line by line in the text box. Please have a look over the code example and the steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, input, and textarea). The div element is just a wrapper for the rest of the elements.
The input element is of type file which provides us the ability to select a file.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected the input element and the textarea using document.querySelector() method and stored them in the input and textarea variables respectively.
We have attached a change event listener to the input element.
In the event handler function, the files property of the input element returns an array of File objects and we are storing that in the files variable.
We are making use of the if statement to verify whether the files array is empty or not. If the user has selected a file, then the length property will always return value greater than 0. If it is 0, we just want to stop the execution of the function by using the return statement.
As you know, arrays have a 0-based index. We are getting the first File object by passing an index of 0 and storing it in the file variable.
We are creating an instance of the FileReader object and storing it in the reader variable.
We are assigning a custom function to the onload property of the FileReader object. This function will be executed when the load event gets fired.
In the load event handler function, we are using the result property to get the contents of the text file.
We are using split() function and passing regex pattern /\r\n|\n/ as a parameter. This will generate an array of lines and we are storing that in the lines variable.
We are using the join() method to join all lines by a newline character (\n). This will return a string and we are setting that string as the value of the textarea element.
We are assigning a custom function to the onerror property of the FileReader object. This function will be executed when an error event gets fired.
In the error event handler function, we are calling the alert() method and passing the name property of the error object as a parameter.
Finally, we are reading the file by calling the readAsText() method and passing the file variable as a parameter.