HTML5 era of pure front-end upload Image preview and strict image format verification function (reprint)

Source: Internet
Author: User

Original address: http://www.2cto.com/kf/201401/274752.html

First, what kind of problem to solve?

Before writing this function, there are children's shoes in the group asked how the pure front-end strictly verify the image format. This was not possible until the HTML5 era, and it had to be uploaded to the background and further verified by the background script reading the text stream. This creates a certain waste of server resources. But in the HTML5 era, we could have done this job at the front end.

On the other hand, in the HTML5 era, many of our original picture preview programs have failed. The reason, in fact, is the modern browser out of the protection of user privacy, file control no longer provide a real physical address, and unified into: C:\fakepath\xxx.xxx such a fake address. However, despair, although the old scheme has failed, but HTML5 has provided us with other ways.

So, how do we solve the above problems? This will take advantage of the file API provided by HTML5. The API we need to use here is "FileReader".

Second, about FileReader

As the name implies, FileReader is the API that HTML5 provides for us to read the file. The function is to read the text stream in the specified format to the cache for JS invocation.

There are four ways to read files in FileReader, the difference of four ways is as follows:
1. readasbinarystring----to read the file as a binary code

2. Readasdataurl----to read the file as Dataurl

3. readastext----to read files as text

4. Readasarraybuffer----to read the file as Arraybuffer

Because we have to do a preview of the picture, we will use the second Readasdataurl method to read the file. So what kind of a format is Dataurl? The following is a screenshot of the Dataurl format of a GIF image.

data:image/gif;base64,r0lgodlhaqabaiaaaaaaaaaaach...ojcacgbqqdageaach5baeaaaaalaaaaaabaaeaqaicraeaow==

The so-called Dataurl format, is actually: data:[file format];base64,[text stream base64 code]

What are the benefits of this format? For the front end, the most intuitive advantage is that it can be written into the IMG tag src, can also be written into the CSS Background-image. This allows you to plug a picture directly into the HTML code or CSS code without having to do the HTTP request one more time.

In this case, a lot of children's shoes may have been a little bit, and then look down.

Three, picture format verification scheme

A child shoe that has done a background verification file format should know that many file formats are with fixed file headers (the text stream at the beginning of the file is a few bytes). Our JPEG, GIF, PNG and other pictures, also have such a file header. So, we are now going through this file header to the image format for strict verification, on the front end, pure JS, do not need to use any background script help.

Just said, Readasdataurl way to read the file, will get the file text stream base64 encoding. So, we just need to compare the first few characters of the Base64 code to know what kind of file format we're going to upload. After my many validations, JPEG, GIF, and PNG Dataurl encoded in the following format:

1 The JPG format is as follows: 2 DATA:IMAGE/JPEG;BASE64,/9J/4 ... 3  4 The PNG format is as follows: 5 data:image/png;base64,ivborw ... 6  7 The GIF format is as follows: 8 Data:image/gif;base64,r0lgod ...

That is, the Base64 encoding of a JPEG picture always starts at the beginning of the/9j/4,png and always ivborw, and the beginning of the GIF is always r0lgod. So, at this point, our verification scheme has actually surfaced.

Iv. image upload preview and validation function

Here is a function that synthesizes all of the above-mentioned knowledge, which I write myself, which is provided to you here:

1 function previewimage (file, prvid) {2 / * File:file control3 * Prvid: Picture preview Container4      */5 var tip = "Expect jpg or png or gif!";//Set Prompt information6 var filters = {7 "JPEG": "/9J/4",8 "gif": "R0lgod",9 "png": "Ivborw"Ten     } One var prvbox = document.getElementById (prvid); A prvbox.innerhtml = ""; - if (window. FileReader) {//HTML5 scenario - for (Var i=0, f; f = file.files[i]; i++) { the var fr = new FileReader (); - fr.onload = function (e) { - var src = e.target.result; - if (!validateimg (src)) { + alert (TIP) - } else { + showprvimg (SRC); A                 } at             } - Fr.readasdataurl (f); -         } - } else {//demote processing - if (!/\.jpg$|\.png$|\.gif$/i.test (File.value)) { - alert (tip); in } else { - showprvimg (file.value); to         } +     } -   the function validateimg (data) { * var pos = Data.indexof (",") + 1; $ For (var e in filters) {Panax Notoginseng if (Data.indexof (filters[e]) = = = pos) { - return e; the             } +         } A return null; the     } +   - function showprvimg (src) { $ var img = document.createelement ("img"); $ img.src = src; - Prvbox.appendchild (IMG); -     } the}

Examples of Use:

1 <  ID= "Files"  type= "file"  onchange= "Previewimage" (This, ' Prvid ') "  multiple=" multiple ">2<   ID= "Prvid"> preview container </div>

Five, compatibility

This function is compatible with Chrome, Firefox, ie6+. However, because the browser below IE9 does not support FileReader, there is a downgrade process when verifying the image format.

HTML5 era of pure front-end upload Image preview and strict image format verification function (reprint)

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.