Browser image selection preview rotation batch upload JS code to achieve

  • 2020-03-30 00:44:56
  • OfStack

Business scenarios encountered in the work, and colleagues together to study, mainly for the compatibility of IE version

In fact, some trivial knowledge points in the online collection of solutions, and then integrated the following points:

1. IE input type=file image preview with IE's filter CSS

      Progid: DXImageTransform. Microsoft. AlphaImageLoader,

    Chrome /firefox USES the File reader for the File API

2. Image rotation, IE with progid: DXImageTransform. Microsoft. The Matrix of the filter, the filter can be combined with, separated by Spaces)

    Chrome/firefox with canvas

3. To upload pictures, I used the invisible form in the iframe to dynamically add input[type=file]. Chrome /firefox works with XHR, but I'm too lazy to change it

4. In order to upload pictures without refreshing this page, and to repeatedly select files, an iframe is also used to maintain a list of input[type=file].

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/2013124164626499.jpg" >

You can refer to the following code, which is mainly one main HTML, and then two iframe HTML. The data returned by the uploaded server is the file name of the successfully uploaded file, which is used to delete the preview.


//On the back to the callback
        //ResultList -> ['file1', 'file2'] is the file name of a successful upload
        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 rotation Angle of the image for submission to the server for processing
            var rotateAng = {};
            //The ordinal number used to name suffixes
            var cc = 0;
            //If it's chrome/ff, you need to use the file API to generate img
            var genImgTpl = function(input, index){
                return '<img src="/webx/public/1.png" class="main" id="img' + index + '" />';
            };
            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.target.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: 'hidden',
                        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"><img src="img/rightBtn.png" /></span>' + 
                    '</div>';
                $('#imgDiv').append(tpl);
                readImgFromInput(_input, index);
            };
            var addAnother = function(){
                $('#uploadBtn').before('<input type="file" name="file" />');
            };
            //Binding events for input[type=file]
            $('#uploadDiv input').live('change', function(){
                var path = this.value;
                if(!path){
                    return;
                }
                showImg($(this));
                addAnother();
            });
            //You can remove input when checkbox
//            $('#imgDiv input:checkbox').live('change', function(){
//                var isChecked = $(this).is(':checked');
//                console.log(isChecked);
//            });
            $('#imgDiv span.turn-right').live('click', function(){
                //The 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);
            });
            //When the form is submitted, delete the unselected input[type=file] according to the checkbox
            $('#uploadBtn').click(function(){
                var choosedNum = $('#imgDiv input:checkbox').filter(':checked').length;
                if(!choosedNum){
                    alert(' Please choose to upload the file! ');
                    return false;
                }
                //The selected ordinal array
                var choosedIndexList = $('#imgDiv input:checkbox').filter(':checked').map(function(){
                    return this.value;
                }).get();
                //Two iframes, one to hold the selected input[type=file]
                //One for the 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);
                    //Rotating 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;
            });
        });

IE7, 8, 9 and chrome tested without problems


Related articles: