HTML5 use FileReader to read file in javascript


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 =[0]; 

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

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);

Leave a Reply

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