Read File Example

This gives an example as to how to read a file in Javascript.

by Brandon Dixon

HTML

<body>
  <description>
    <p>
    Select a file, click submit, and watch the contents appear below.
    </p>
    <form id='form'>
      <input type='file' id='fileBrowse'>
      <input type='submit' value='Submit'>
    </form>
  </description>
  <fileContents>
    
  </fileContents>
</body>

CSS

fileContents p {
  background-color: rgba(0,0,255,0.2);
}

JavaScript

document.getElementById("form").onsubmit = function(e) {
		var file = document.getElementById('fileBrowse').files[0]; //for this example, get first file ONLY
    getFileContents(file,function(contents) {
    		document.getElementsByTagName("fileContents")[0].innerHTML = "<p>"+contents+"</p>";
    });
    e.preventDefault();
}

/**
* This will read a file, then execute a function with the contents
* @param file to read
* @param function to execute upon load
*/
function getFileContents(file,func) {
		var reader = new FileReader();
    var contents;
    reader.onload = function(e) {
        func(reader.result);
		}
    reader.readAsText(file);
}