Wagtail Wagtail - 1 year ago 105
Javascript Question

Upload File as String to JavaScript Variable

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.

Thanks in advance!

Answer Source

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');

        filecontent = evt.target.result;

        document.forms['myform'].elements['text'].value = evt.target.result;


Here's the associated HTML form:

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

and a jsfiddle to demo it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download