JS Upload image & Preview (FileReader)

Source: Internet
Author: User

FileReader

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

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

    • Method Name Parameter Description
    • Abort None Interrupt Read
    • Readasbinarystring file reads files as binary code
    • Readasdataurl file reads files as Dataurl
    • Readastext file, [encoding] reads files 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 the string is the data URL, (that is, the Base64 string submitted to the background), the data A URL is a scheme for embedding small files directly into a document. Small files here usually refer to files in the format of images and HTML.

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 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 read

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.

4. A chestnut that uploads images and previews (not uploaded to the background)

HTML section

<type= "file"  name= "file"  onchange= "Showpreview (this) "/><style=" width:100px;height:100px; " ID = "img" />

JS section

function Showpreview (source) {        console.log (source);//Is this INPUT element        var file = source.files[0];        if (window. FileReader) {            var ofreader = new FileReader ();            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            var sreg =/^ (?: image\/bmp|image\/cis\-cod|image\/gif|image\/ ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\- raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\- Graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump) $/i ;            if (!sreg.test (File.type)) {                alert ("Only allow uploading of picture files");            }            Ofreader.onloadend = function (e) {                document.getElementById ("img"). src = e.target.result;            };            Ofreader.readasdataurl (file);        }    }

js uploading pictures & Previews (FileReader)

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.