The use of the FileReader of HTML5

Source: Internet
Author: User

HTML5 defines FileReader as an important member of the file API for reading files, and the FileReader interface provides a way to read the file and an event model that contains the read result, according to the definition of the system.

FileReader is very simple to use, you can create a FileReader object and invoke its methods as follows:

1. Detection of browser support for FileReader

if (window.      FileReader) {var fr = new FileReader ();  Add your code here} else {alert ("not supported by your browser!"); }

2. Methods for invoking FileReader objects

filereader instance has 4 methods, 3 of which are used to read the file and the other to interrupt the read. The following table lists these methods, along with their parameters and capabilities, and it is important to note that the method does not return read results regardless of the success or failure of the read, which is stored in the   result property.

parameter description
abort none interrupt read
readasbinarystring file read the file as a binary code
readasdataurl file read the file as Dataurl
Readastext file, [encoding] To read a file as text


3. Handling Events

The FileReader contains a complete set of event models that capture the state of the file when it is read, and the following table summarizes these events.

Event Description

Triggered when Onabort interrupts

OnError triggered when an error occurs

The onload file is triggered when the read completes successfully

Onloadend Read completion trigger, regardless of success or failure

Onloadstart trigger at start of Read

OnProgress Read in

Once a file begins to read, the result property of the instance is populated, regardless of success or failure. If the read fails, the value of result is null, otherwise it is the result of the read, and the vast majority of programs will fetch the value when the file is successfully read.

Fr.onload = function () {this.result; };

    • The following shows the use of FileReader with an upload image preview and a progress bar upload.

<script type= "Text/javascript" >          function  showpreview (source)  {               var file = source.files[0];               if (window. FileReader)  {                   var fr = new filereader ();                   fr.onloadend = function (e)  {                        document.getelementbyid ("Portrait") .src = e.target.result;                   };                   Fr.readasdataurl (file);               }           }      </script >    <input type= "File"  name= "file"  onchange= "Showpreview (This)"  />  

If you want to limit the type of upload file, you can get the file object through the file selector and check the file type with the Type property

if (!/image\/\w+/.test (File.type)) {alert ("Make sure the file is an image type");  return false; }

It is not difficult to find that this detection is based on regular expressions, so it is useful to have a variety of complex matches.

If you want to add a progress bar, you can use the progress tag of HTML 5, implemented by the following code.

<form>      < fieldset>          <legend> Read File:</legend>           <input type= "File"  id= "file"  / >          <input type= "button"  value= "Interrupt"  id= "Abort"  />          <p>               <label> Read Progress:</label>< Progress id= "Progress"  value= "0"  max= "></progress>     "      </p>          <p  id= "Status" ></p>      </fieldset>  </form> 
Var h = {      init: function ()  {           var me = this;                       document.getElementById (' File ') .onchange = me.filehandler;           document.getelementbyid (' Abort ') .onclick = me.aborthandler;                       Me.status = document.getelementbyid (' status ');           me.progress = document.getelementbyid (' Progress ');           me.percent = document.getelementbyid (' percent ');                      me.loaded = 0;           //per read 1m          me.step =  1024 * 1024;          me.times = 0 ;       },      filehandler: function (e)   {          var me = h;                       var file = me.file = this.files[0];                      var reader =  Me.reader = new filereader ();                      //          me.total =  file.size;                      reader.onloadstart = me.onLoadStart;           reader.onprogress = me.onProgress;           reader.onabort = me.onAbort;           reader.onerror = me.onerror;           reader.onload = me.onLoad;           reader.onloadend = me.onloadend;          //Read the first block           me.readblob (file, 0);       },       onloadstart: function ()  {           var me = h;      },       Onprogress: function (e)  {          var me  = h;                      me.loaded += e.loaded;           //Update progress bar           me.progress.value =   (me.loaded / me.total)  * 100;      },       onabort: function ()  {           var me = h;      },       Onerror: function ()  {          var me = h;                  },       onload: function ()  {          var me  = h;             if (me.loaded  < me.total)  {               me.readblob (me.loaded);           } else {               me.loaded =  me.total;          }      },       onloadend: function ()  {           var me = h;                  },      readblob: function (start)  {           var me = h;                      var blob,               file = me.file;                       me.times += 1;                      if (File.webkitslice)  {               blob = file.webkitslice (start, start +  me.step + 1), &Nbsp;         } else if (File.mozSlice)  {               blob = file.mozslice ( START,&NBSP;START&NBSP;+&NBSP;ME.STEP&NBSP;+&NBSP;1);           }                      me.reader.readastext (BLOB);      },       aborthandler: function ()  {           var me = h;                      if (Me.reader)  {               me.reader.abort ();           }  &Nbsp;   }  };     h.init (); 


The use of the FileReader of HTML5

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.