Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  179] [ 6]  / answers: 1 / hits: 32002  / 12 Years ago, fri, january 4, 2013, 12:00:00

Is there any way for a client to upload a file in an HTML form (e.g. .txt or .csv formats) to a JavaScript variable as a string using only JavaScript? If so, could you provide a simple example? I don't want to use any PHP.


More From » forms

 Answers
27

Here is a quick and dirty example based on a form named myform that contains a file input named 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 associated 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 a jsfiddle to demo it.


[#81084] Thursday, January 3, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamilab

Total Points: 687
Total Questions: 88
Total Answers: 86

Location: Antigua and Barbuda
Member since Sat, Apr 24, 2021
3 Years ago
jamilab questions
;