JS upload Picture preview plug-in production (compatible to IE6) _javascript tips

Source: Internet
Author: User

One, the realization picture previews some methods.

Understand, in fact, the methods are similar. There are probably several ways to do this:

① Subscription Input[type=file] element's onchange event.

Once the selected path is changed, upload the picture to the server, and then return the image on the server side of the address, and assign the value to the IMG element.

Disadvantages: A lot of work, some upload is not the user eventually need to upload pictures, but this way will upload the selected pictures are saved to the server side, will cause waste of resources, and the server side of the temporary cleanup of those preview pictures also need a certain amount of work.

② utilizes the new characteristics of HTML5 FileReader.

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

Disadvantage: The data URI scheme obtained through the FileReader Readasdataurl method generates a string of very long base64 strings, and if the picture is larger then the string is longer, which can cause performance degradation if the page appears reflow. and browser support is inconsistent, supported browsers: ff3.6+,chrome7+,ie10+.

③ uses Windows. Url.createobjecturl replaces FileReader with DXImageTransform.Microsoft.AlphaImageLoader filters compatible with IE.

Disadvantage: Due to IE11 security considerations, it is impossible to get the real address of the user's chosen file through value, outerHTML, and GetAttribute on the input[type=file] element, only

D:\frontEnd\ file name. So 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, which 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 HTML

<div id= "pic" >

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

Do you want to say so easy?

② second step, plug-in JS package.

1, the establishment of objects

I mainly adopted a combination of inheritance, encapsulated two methods, is a single picture upload and more than one picture upload. Because whether it is a single picture upload or a single picture upload, you need to pass in, upload the image of the input button, IMG tags, wrapped with img Div, the largest single picture of the value, in kilobytes. So these four parameters will be passed in when you create the upload image object. The method for creating the object is as follows:

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

2. Define matching pattern

Because it is uploaded pictures, in addition to the input inside the accept= "image/*", made a preliminary limit, but also need a JS regular to pass the path of detection to determine whether the picture. So define the pattern on prototype for two methods:

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

3. Definition method

The main thing is to judge whether it is below the IE11 environment and write two kinds of programs. The first is directly through the change of IMG src to preview the picture, the second is in the lower version of IE, through the filter to achieve the preview effect.

FF, Chrome, IE11 above: (Here are more than one picture preview code)

<span class= "Apple-tab-span" > if (maxpics) {</span> <br> if (this.fileObj.files && This.fileobj.files[0]) {
var imgs=this.picwrap.queryselectorall (' img ');//Find out how many images there are in the Dom
var num= Imgs.length;
var html=this.picwrap.innerhtml;
if (number (num) <number (maxpics)) {//To determine if the maximum upload limit is exceeded
if (num==1&&!imgs[0].classlist.contains (' Newload ')) {//overwrite the first default picture
html= ';
}
if (This.pattern.test (Fileobj.files[0].name)) {
if (judgesize (fileobj.files[0].size/1024,this.maximgsize)) {// Determine whether the size of the picture is overrun html= '  ' +html;
this.picwrap.innerhtml=html;
} else{
alert (' You upload a picture too big! ');
}
} else{
alert (' You didn't upload it as if it wasn't a picture. Oh, please check! ');
}
} else{
alert (' Upload ' +maxpics+ ' picture at most each time! ');
}
}

IE11 using filters to achieve the effect:

The Var nums=this.picwrap.childnodes.length;//is judged by the length of the ChildNodes
if (nums<) because IE6 the following methods do not support Queryselectorall MAXPICS+2) {//here plus 2 is because there would have been a default picture, and ChildNodes read the length will be more than 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 must set the size of the Div
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 (' The image you uploaded is wrong format, please choose again! ');
return false;
}
This.preview.style.display= ' None ';
Document.selection.empty ();
} else{
alert (' You upload a picture 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);
The definition uploads the picture object, the parameter is to upload the picture the input button, the IMG label package, wraps the IMG Div, the biggest single picture value, the unit is KB
obj.uploadsinglepic (200,250); Parameters for each width, height
//obj.uploadpics (200,250,2),//Multiple picture upload, parameters for each width, height, upload a maximum number of cards
</script>

The above is a small series to introduce JS upload picture preview plug-in production (compatible to IE6) of the relevant knowledge, hope to help everyone, if you have any questions welcome to my message, small series will promptly reply to everyone!

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.