Home > Web Front-end > JS Tutorial > body text

JS code implementation for browser image selection, preview, rotation, and batch upload_javascript skills

WBOY
Release: 2016-05-16 17:10:53
Original
1218 people have browsed it

I studied the business scenarios I encountered at work with my colleagues, mainly for compatibility with the IE version

In fact, I collected some trivial knowledge points and solutions on the Internet, and then integrated them. The main points are as follows:

1. IE input type=file image preview requires IE’s filter css

progid:DXImageTransform.Microsoft.AlphaImageLoader

Chrome/firefox uses the file reader of File api

2. For image rotation, IE uses the filter of progid:DXImageTransform.Microsoft.Matrix (filters can be combined and separated by spaces)

Use canvas for chrome/firefox

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

4. In order to upload images without refreshing this page, and to be able to select files repeatedly, an iframe is used to maintain a list of input[type=file], which is quite clever.

JS code implementation for browser image selection, preview, rotation, and batch upload_javascript skills

You can refer to the code below, which is mainly a 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 image.

Copy code The code is as follows:

// 上传回调
        // resultList -> ['file1', 'file2'] 为上传成功的file name
        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(){
// 保存图片旋转的角度,以便提交给服务端处理
var rotateAng = {};
// 用于命名后缀的序号
var cc = 0;

// 如果是chrome/ff,需要用file api去生成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.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 = '

' + genImgTpl(_input, index) +
                    '' +
                    '' +
                    '
';
                $('#imgDiv').append(tpl);

                readImgFromInput(_input, index);
            };
            var addAnother = function(){
                $('#uploadBtn').before('');
            };

            // input[type=file]的绑定事件
            $('#uploadDiv input').live('change', function(){
                var path = this.value;
                if(!path){
                    return;
                }

                showImg($(this));
                addAnother();
            });

            // 可以在checkbox时候remove input
//            $('#imgDiv input:checkbox').live('change', function(){
//                var isChecked = $(this).is(':checked');
//                console.log(isChecked);
//            });

            $('#imgDiv span.turn-right').live('click', function(){
                // 上次旋转的角度
                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);
            });

            // 表单提交时候根据checkbox,删除未choose的input[type=file]
            $('#uploadBtn').click(function(){
                var choosedNum = $('#imgDiv input:checkbox').filter(':checked').length;
                if(!choosedNum){
                    alert('请选择上传文件!');
                    return false;
                }

                // 选中的序号数组
                var choosedIndexList = $('#imgDiv input:checkbox').filter(':checked').map(function(){
                    return this.value;
                }).get();

                                                                                                                                                                                                                  .
var chooseIframe = $('#choose')[0].contentWindow;

var i = 0;

for(; i < chosenIndexList.length; i ){

var index = chosenIndexList[i];
      var inputFile = chooseIframe.$('#uploadDiv input' ).filter('[data-index=' index ']');
           uploadIframe.$('#uploadForm').append(inputFile);

                                                                                                                                          var tplInput = '';                                                                                  }


uploadIframe.doUpload();

              return false;
           });

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template