HTML5 use FileReader to read file in javascript

FileReader

One simple way to access local files is via the <input type=”file” /> HTML form element. That will give you access to readonly
information for an individual file such as its name, size, mimetype, and a reference to the file handle. Adding the “multiple” attribute to the file input element (as in <input multiple=”multiple” type=”file” /> will get you a list of files to work with.

<input id="fileinput" type="file" />
 <script type="text/javascript">
  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0]; 

    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
	      var contents = e.target.result;
        alert( "Got the file.n" 
              +"name: " + f.name + "n"
              +"type: " + f.type + "n"
              +"size: " + f.size + " bytesn"
              + "starts with: " + contents.substr(1, contents.indexOf("n"))
        );  
      }
      r.readAsText(f);
    } else { 
      alert("Failed to load file");
    }
  }

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
 </script>

Leave a Reply

Your email address will not be published. Required fields are marked *