Fill textarea from a file upload javascript

2 months ago  |  55 views
To select the file, put <input type="file" id="localFileInput"> in the HTML wherever you want the file selection box to be. Then, add some JavaScript just before the closing script tag in your dashboard that handles the contents of the file. You'll need to include something like:

var control = document.getElementById("localFileInput")

add an event listener:

control.addEventListener("change", function(event){...

and inside that function you can use FileReader() to read the contents of the local file.

EDITED RESPONSE BELOW:

Assuming the user will be selecting the file, try the following:

Select the local file:

 <input type="file" id="inputfile"/>

A blank textarea that will be populated by the contents of your text file:

 <textarea rows="4" cols="50" id="putcontentshere"></textarea>

The javascript needed to put the contents of the file in the textarea (this goes just above the closing script tag in the body of the html):

//External data file handling starts here
var control = document.getElementById("inputfile"); 
 control.addEventListener("change", function(event){ 
 var reader = new FileReader(); 
 reader.onload = function(event){
 var contents = event.target.result; 
 document.getElementById('putcontentshere').value = contents; 
 }; 
 reader.onerror = function(event){
 console.error("File could not be read! Code " + event.target.error.code);
 }; 
 console.log("Filename: " + control.files[0].name);
 reader.readAsText(control.files[0]); 
 }, false);

Simple as that. If you want to do it without the user selecting the file, I think you might be out of luck. Allowing the browser/DOM to access the local file system without user interaction would be a big no-no and isn't allowed (that I know of) without hacking something.