JS Image upload Preview plugin production (compatible to IE6)

Source: Internet
Author: User

In fact, the picture preview feature is very common. It was a surprise that I didn't need a preview before I had a picture uploaded, and I didn't realize it. Now the project in hand needs to have a picture preview function, so I made a small plug-in. Share your ideas here.

First, some ways to achieve picture preview.

Understand, in fact, the method is very similar. There are several ways to do this:

① the onchange event that subscribes to the input[type=file] element.

Once the selected path is changed, the image is uploaded to the server, then the address on the server side of the image is returned and assigned to the IMG element.

disadvantage: heavy workload, some upload is not the end user need to upload pictures, but this way will upload the selected images are saved to the server side, will cause the waste of resources, and the server-side cleanup Temporary preview Pictures also need a certain amount of work.

② uses the new features of HTML5 FileReader.

This object provides a number of related methods, the most important of which is the Readasdataurl method. Point I know more.

Disadvantage: The data URI scheme obtained by FileReader's Readasdataurl method generates a long string of base64 strings that are longer if the image is larger, which can cause performance degradation if the page is reflow. and browser support is inconsistent, supported browsers: ff3.6+,chrome7+,ie10+.

③ Use window. Url.createobjecturl instead of FileReader, then use the DXImageTransform.Microsoft.AlphaImageLoader filter compatible with IE.

disadvantage: due to IE11 security considerations, so that the input[type=file] element through the value, outerhtml and getattribute way can not obtain the user's chosen file real address, can only get to

The D:\frontEnd\ file name. Therefore, you need to use the Document.selection.createRangeCollection method to get the real address.

Second, my plug-in production

I chose a more conservative approach, that is, the third use of window. Url.createobjecturl instead of FileReader, and then use DXImageTransform.Microsoft.AlphaImageLoader filter compatible with IE method.

① The first step, the layout of the HTML

<div id= "pic" ></div><input type=" file "id=" uploadbtn "accept=" image/* "onchange=" SetPreviewPic () ">

Do you want to say so easy?

② The second step, the plugin JS package.

1. Set up objects

I mainly use a combination of inheritance, encapsulated two methods, respectively, is a single image upload and multiple images upload. Because whether it is a single image upload or a single image upload, you need to pass in, upload the image of the input button,img tag, wrapped in the IMG Div, the largest single photo of the value, in kilobytes. So these four parameters are passed in when creating an object to upload images. Here's how to create the object:

var setpreviewpic=function (fileobj,preview,picwrap,maximgsize) {this.fileobj=fileobj; this.preview=preview; This.picwrap=picwrap; This.maximgsize=maximgsize;}

2. Define the matching mode

Because it is uploading pictures, in addition to input inside add accept= "image/*", do a preliminary limit, but also need a JS regular to pass the path detection to determine whether it is a picture. So the pattern is defined on the prototype for two ways to use:

Setpreviewpic.prototype.pattern=new RegExp (' \. ( Jpg|png|jpeg) +$ ', ' I ');

3. Definition method

The main is to judge whether the environment is lower than IE11, to write two kinds of programs. The first is to preview the image directly by changing the IMG SRC, and the second is to use the filter to achieve the preview effect in the lower version of IE.

FF, Chrome, IE11 above: (The code for multiple image previews is posted here)

if (maxpics) {
if (This.fileObj.files && this.fileobj.files[0]) {var imgs=this.picwrap.queryselectorall (' img '); Find out how many images are in the DOM var num=imgs.length;var html=this.picwrap.innerhtml; if (number (num) <number (maxpics)) {//determines if the maximum upload limit is exceeded if (num==1&& (!imgs[0].classlist.contains (' newload ') ) {//overwrite the first default image html= '; } if (This.pattern.test (fileobj.files[0].name)) {if (Judgesize (Fileobj.files[0].size/1024,this.max Imgsize) {//Determine if the size of the picture is html= ' ' +html; this.picwrap.innerhtml=html; }else{alert (' The picture you uploaded is too big! ‘); }}else{alert (' You're uploading something that doesn't seem like a picture oh, please check! ‘); }}else{alert (' Upload a maximum of ' +maxpics+ ' photos at a time! ‘); } }

IE11 using filters to achieve the effect:

 var nums=this.picwrap.childnodes.length;//because IE6 does not support the Queryselectorall method,        By the length of the childnodes to determine if (nums<maxpics+2) {//Here Add 2 is because there is a default picture, and ChildNodes read out the length will be 1 this.fileObj.select ();        if (document.selection) {var imgsrc=document.selection.createrange (). text;                var image=new image ();                IMAGE.SRC=IMGSRC;          Filesize=image.filesize;        if (Judgesize (image.filesize/1024,this.maximgsize)) {//ie, the size of the div must be set to Var ele=document.createelement (' div ');        ele.style.width=width+ ' px ';        ele.style.height=height+ ' px ';        Ele.style.filter= "Progid:DXImageTransform.Microsoft.AlphaImageLoader (sizingmethod=scale,src= '" +imgsrc+ ")";        try{This.picWrap.appendChild (ele); }catch (e) {alert (' You have uploaded an incorrect image format, please re-select!        ‘);        return false;        } this.preview.style.display= ' None ';    Document.selection.empty (); }else{alert (' The picture you uploaded is too big!    ‘); }}

Now, it's done!

Usage:

<script type= "Text/javascript" src= ". /js/singlepic.js "></script><script>    var fileobj=document.getelementbyid (' uploadbtn ');    var Preview=document.getelementbyid (' preview ');    var Picwrap=document.getelementbyid (' pic ');    Fileobj.onchange=function () {        var obj=new setpreviewpic (fileobj,preview,picwrap,100);        Define the upload Image object, the parameters are the input button to upload the image, the IMG tag package, the IMG-wrapped Div, the largest single photo value, in KB        obj.uploadsinglepic (200,250);//single picture upload, The parameters are the width, height        /obj.uploadpics (200,250,2) of each sheet respectively;  Multiple images uploaded, parameters for each width, height, the maximum number of uploads    }</script>

done! For complete projects, please click on my github! Welcome to pay attention, give me a point a start Oh! ^_^

However, here is one is actually no way to determine whether the client will not be a picture of the file by modifying the suffix name to upload, only through the server side to judge!

JS Image upload Preview plugin production (compatible to IE6)

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.