JS Code Implementation of browser Image Selection for preview, rotation, and batch upload

Source: Internet
Author: User

I worked with my colleagues on the business scenarios I encountered at work to ensure compatibility with the IE version.

In fact, some trivial knowledge points are collected and solved on the Internet, and then integrated, mainly including the following:

1. for IE input type = file image preview, use the filter css of IE.

Progid: DXImageTransform. Microsoft. AlphaImageLoader

Chrome/firefox uses File reader of file api

2. image rotation. IE uses the filter of progid: DXImageTransform. Microsoft. Matrix (filters can be used in combination and separated by spaces)

Canvas for chrome/firefox

3. upload images. I use an invisible iframe to dynamically add input [type = file] to form. Chrome/firefox can use xhr, but I am too lazy to modify it.

4. In order to upload images without refreshing this page, you can select files repeatedly. Therefore, an iframe is used to maintain a list of input [type = file], which is a coincidence.

You can refer to the code below, mainly a main html, and then two iframe html. The data returned by the uploaded server is the uploaded file name, which is used to delete the preview image.
Copy codeThe Code is as follows:
// Upload callback
// ResultList-> ['file1', 'file2'] indicates the name of the uploaded file.
Var uploadCallback = function (resultList ){
Console. log (JSON. stringify (resultList ));

Var I = 0;
For (; I <resultList. length; I ++ ){
Var index = resultList [I]. substr ('file'. length );
$ (': Checkbox [value =' + index + ']'). parent (). parent (). remove ();
}
};

$ (Function (){
// Save the image rotation angle for submission to the server for processing
Var rotateAng = {};
// The serial number used to name the suffix
Var cc = 0;

// For chrome/ff, use the file api to generate img
Var genImgTpl = function (input, index ){
Return ' ';
};

Var readImgFromInput = function (_ input, index ){
Var inputDom = _ input [0];
// Chrome/ff
If (inputDom ['files']) {
Var reader = new FileReader ();
Reader. onload = function (e ){
$ ('Img. main: last'). attr ({src: e.tar get. result });
}
Reader. readAsDataURL (inputDom ['files'] [0]);
} Else {
Var src = _ input [0]. value;

Var imgDom =$ ('# img' + index );
ImgDom. attr ('src-old', src );
ImgDom.css ({
Float: 'left ',
Position: 'relative ',
Overflow: 'ddy ',
Width: '195px ',
Height: '195px'
});

ImgDom.css ({'filter': "progid: DXImageTransform. microsoft. alphaImageLoader (enabled = 'true', sizingMethod = 'Scale', src = \ "" + src + "\")"});
}
};

Var showImg = function (_ input ){
Var index = ++ cc;

_ Input. addClass ('hide ');
_ Input. attr ('name', 'file' + index );
_ Input. attr ('data-Index', index );

Var iframeWin = $ ('# choose') [0]. contentWindow;
IframeWin. addInput (_ input );

Var tpl = '<div>' + genImgTpl (_ input, index) +
'<Span class = "choose"> <input type = "checkbox" value = "' + index + '" checked = "true"/> </span>' +
'<Span class = "opts turn-right"> </span>' +
'</Div> ';
$ ('# ImgDiv'). append (tpl );

ReadImgFromInput (_ input, index );
};
Var addAnother = function (){
$ ('# UploadBtn'). before ('<input type = "file" name = "file"/> ');
};

// Input [type = file] binding event
$ ('# UploadDiv input'). live ('change', function (){
Var path = this. value;
If (! Path ){
Return;
}

ShowImg ($ (this ));
AddAnother ();
});

// You can remove input in the checkbox.
// $ ('# ImgDiv input: checkbox'). live ('change', function (){
// Var isChecked = $ (this). is (': checked ');
// Console. log (isChecked );
//});

$ ('# ImgDiv span. turn-right'). live ('click', function (){
// Angle of last rotation
Var index = $ (this). siblings ('span. choose '). find ('input'). val ();
Var oldAng = rotateAng [index] | 0;
Var newAng = oldAng + 90;
RotateAng [index] = newAng;

$ ('# Img' + index). rotate (90 );
});

// Delete the input [type = file] without choose according to the checkbox when the form is submitted
$ ('# UploadBtn'). click (function (){
Var choosedNum = $ ('# imgDiv input: checkbox'). filter (': checked'). length;
If (! ChoosedNum ){
Alert ('select Upload File! ');
Return false;
}

// The selected sequence number Array
Var choosedIndexList = $ ('# imgDiv input: checkbox'). filter (': checked'). map (function (){
Return this. value;
}). Get ();

// Two iframe, one used to save the selected input [type = file]
// A form upload
Var uploadIframe = $ ('# upload') [0]. contentWindow;
Var chooseIframe = $ ('# choose') [0]. contentWindow;

Var I = 0;
For (; I <choosedIndexList. length; I ++ ){
Var index = choosedIndexList [I];
Var inputFile = chooseIframe. $ ('# uploadDiv input'). filter ('[data-index =' + index + ']');
UploadIframe. $ ('# uploadForm'). append (inputFile );

// Rotation Degree
Var ang = rotateAng [index] | 0;
If (ang %360! = 0 ){
Var tplInput = '<input type = "hide" name = "ang" + index +' "value =" '+ ang +' "/> ';
UploadIframe. $ ('# uploadForm'). append (tplInput );
}
}

UploadIframe. doUpload ();

Return false;
});
});

Test in IE7, 8, 9, and chrome

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.