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. Detecting browser support for FileReader [JavaScript] view plain copyif(window. FileReader) {varFR =NewFileReader (); //Add your code here    }      Else{alert ("Not supported by your browser!"); }  2The instance of the method FileReader that calls the FileReader object has4 methods, of which 3one 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. The method name parameter describes the abort none interrupt read Readasbinarystring file reads files as binary code Readasdataurl file reads files as Dataurlreadast ext file, [encoding] reads the file as text Readastext: The method has two parameters, where the second parameter is the encoding of the text, and the default value is UTF-8. This method is very easy to understand, the file is read in text mode, the result of reading is the content of this text file. Readasbinarystring: This method reads a file as a binary string, usually we pass it to the back end, and the backend can store the file through this string. Readasdataurl: This is the method used in the example program, which reads a file as a string beginning with data: The essence of this string is that the data Url,data URL is a scheme to embed small files directly into the document. Small files here usually refer to files in the format of images and HTML. 3The handling event FileReader contains a complete set of event models for capturing the state of the file when it was read, and the following table summarizes these events.    Event description Onabort triggered when an onerror error occurs when triggering an onload file when a read completes successfully, triggering a onloadend read completion trigger, regardless of success or failure Onloadstart the start of the Read trigger OnProgress Once a file is read, the result property of the instance will be populated, regardless of success or failure. If the read fails, the value of result isNULL, otherwise it is the result of reading, most of the program will fetch the value when the file is successfully read. [JavaScript] View plain copy fr.onload=function() {           This. Result;  }; The following shows the use of FileReader with an upload image preview and a progress bar upload. [HTML] View plain copy<script type= "Text/javascript" >functionShowpreview (source) {varFile = Source.files[0]; if(window. FileReader) {varFR =NewFileReader (); 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 by using the Type property [JavaScript] View plain copyif(!/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. [HTML] View plain copy<form> <fieldset> <legend>:</legend> read files <input type= "file                  "Id=" File "/> <input type=" button "value=" Interrupt "id=" Abort "/> <p> <label> Read progress: </label><progress id= "Progress" value= "0" max= "+" ></progress> &LT;/P&G              T <p id= "Status" ></p> </fieldset> </form>[JavaScript] view plain copyvarh ={init:function() {              varme = 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; //1M per readMe.step = 1024 * 1024; Me.times= 0; }, Filehandler:function(e) {varme =h; varFile = Me.file = This. files[0]; varReader = Me.reader =NewFileReader (); //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 blockMe.readblob (file, 0); }, Onloadstart:function() {              varme =h; }, OnProgress:function(e) {varme =h; me.loaded+=e.loaded; //Update progress barMe.progress.value = (me.loaded/me.total) * 100; }, Onabort:function() {              varme =h; }, OnError:function() {              varme =h; }, OnLoad:function() {              varme =h; if(Me.loaded <me.total) {Me.readblob (me.loaded); } Else{me.loaded=Me.total; }}, Onloadend:function() {              varme =h; }, Readblob:function(start) {varme =h; varblob, File=Me.file; Me.times+ = 1; if(file.webkitslice) {blob= File.webkitslice (start, start + Me.step + 1); } Else if(file.mozslice) {blob= File.mozslice (start, start + Me.step + 1);          } me.reader.readAsText (BLOB); }, Aborthandler:function() {              varme =h; if(Me.reader) {me.reader.abort ();             }          }      };   H.init (); 

The use of the FileReader of HTML5

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.