Upload file as string to JavaScript variable

Is there a way for a client to load an HTML file (e.g. .txt or .csv) into a JavaScript variable as a string using only JavaScript? If so, can you provide a simple example? I do not want to use PHP.

Thanks in advance!

+7
source share
2 answers

Here is a quick and dirty example based on a form called "myform" that contains an input file called "myfile":

document.forms['myform'].elements['myfile'].onchange = function(evt) { if(!window.FileReader) return; // Browser is not compatible var reader = new FileReader(); reader.onload = function(evt) { if(evt.target.readyState != 2) return; if(evt.target.error) { alert('Error while reading file'); return; } filecontent = evt.target.result; document.forms['myform'].elements['text'].value = evt.target.result; }; reader.readAsText(evt.target.files[0]); }; 

Here's the corresponding HTML form:

 <form id="myform"> <p> <input id="myfile" name="files[]" multiple="" type="file" /> <textarea id="text" rows="20" cols="40">nothing loaded</textarea> </p> </form> 

and jsfiddle to demonstrate it.

+5
source

This yent answer option manages multiple downloads and uses jquery:

HTML:

 <form id="myform"> <p> <input id="myfile" name="files[]" multiple="" type="file" /> <textarea id="text" rows="20" cols="40">nothing loaded</textarea> </p> </form> 

script:

 $("#myfile").on("change", function (changeEvent) { for (var i = 0; i < changeEvent.target.files.length; ++i) { (function (file) { // Wrap current file in a closure. var loader = new FileReader(); loader.onload = function (loadEvent) { if (loadEvent.target.readyState != 2) return; if (loadEvent.target.error) { alert("Error while reading file " + file.name + ": " + loadEvent.target.error); return; } console.log(loadEvent.target.result.length); // Your text is in loadEvent.target.result }; loader.readAsText(file); })(changeEvent.target.files[i]); } }); 

Its useful to note:

  • You must use one FileReader for each (parallel) file. Otherwise, you will see an exception, for example, The object is already busy reading .
  • LoadEvent callbacks will be called in random order, probably depending on the size of the load.
  • Closing loadEvent will see the value of i that ended the loop.
  • FileReader results are not arrays; they do not have for each.

This jsfiddle daemon saves the load order by posting the div in the change handler.

+3
source

All Articles