WebUploader 同一页面中集成 多实例,单图上传,多图上传,编辑回显,删除(包括逻辑删除,显示移除)

来源:互联网 发布:ui需要编程吗 编辑:程序博客网 时间:2024/06/06 07:44

(zlt尼玛银行)原创文章,转载请注明出处!http://blog.csdn.net/weixin_35890630/article/details/52805528


介于大家的要求我把demo放到了github上,地址:https://github.com/lishuqi/WebUploaderDemo,

这个Demo是基于java的,框架使用Spring+SpringMVC+MyBatis+Maven实现的,数据库使用mysql(只有一张表)

fork的时候顺带star噢~~~



百度 WebUploader

1.最近项目中需要使用 WebUploader来做图片上传,主要功能:

 同一页面中:

添加

a:实现身份证上传,(限制webuploader只能上传一个图片,删除)

b:为微信端和网页端提供封面图片,(限制webuploader只能上传一个图片,删除)

c:附件上传(可以实现多图上传,删除)

效果图:


编辑功能点:

a:图片的回显

b:删除上传

查看功能点:

a:回显

b:不能进行删除,上传等操作


代码实现

前台组件html:

                                          <div class="uploder-container">                              <div  class="cxuploder">                            <div class="queueList">                                <div class="placeholder">                                    <div class="filePicker"></div>                                    <p>将照片拖到这里</p>                                </div>                            </div>                                                        <div class="statusBar" style="display:none;height:50px;" >                                <div class="btns">                                    <div  class="jxfilePicker"></div>                                </div>                                <div class="info"></div>                            </div>                        </div>                    </div>



首先是多实例:

       思路,在一个页面中实现多实例,那么页面会有多个div等组成的webuploader组件,他们的div格式等都是相同的。那么就可以循环初始化这些组件,核心代码如下:

//循环页面中每个上传域       $('.uploder-container').each(function(index){//index为标识是页面中第几个webuploader组件    console.log(index);    // 添加的文件数量            var fileCount = 0;            // 添加的文件总大小            var fileSize = 0;    var filePicker=$(this).find('.filePicker');//上传按钮实例    var queueList=$(this).find('.queueList');//拖拽容器实例    var jxfilePicker=$(this).find('.jxfilePicker');//继续添加按钮实例    var placeholder=$(this).find('.placeholder');//按钮与虚线框实例    var statusBar=$(this).find('.statusBar');//再次添加按钮容器实例    var info =statusBar.find('.info');//提示信息容器实例        // 图片容器           var queue = $('<ul class="filelist"></ul>').appendTo( queueList);    //一次性可以上传多少张图                  var i =0;    if(index == 2){ //附件上传时可以上传50张最多     i = 50;    }else{    i=1;//身份证,封面图片只能上传一张    }        //初始化上传实例                uploader[index] = WebUploader.create({                 pick: {                    id: filePicker,                    label: '上传'                },                dnd: queueList,                               //这里可以根据 index 或者其他,使用变量形式                accept: {                    title: 'Images',                    extensions: 'gif,jpg,jpeg,bmp,png,doc',                    mimeTypes: 'image/*'                },                // swf文件路径                swf: 'static/res/Uploader.swf',   //ie下很重要               disableGlobalDnd: true,//禁用浏览器的拖拽功能,否则图片会被浏览器打开                chunked: false,//是否分片处理大文件的上传                                            server: 'uploadEnsour.do',//上传地址    //后台接受地址                                fileNumLimit: i,//一次最多上传文件个数                                fileSizeLimit: 10 * 1024 * 1024,    // 总共的最大限制10M                                fileSingleSizeLimit: 3 * 1024 * 1024 ,   // 单文件的最大限制3M                                auto :true,                                formData: {                                token:index//可以在这里附加控件编号,从而区分是哪个控件上传的   这个是webuploader组件的index,可以在后台获取到token值,也可以添加其他值以供后台获取                }            });                if(index == 2){  //index==1和0时,我这里是封面图片和身份证正面照片,所以就不让他显示。index == 2 时是附件上传所以将其显示可以进行继续添加            // 添加“添加文件”的按钮                uploader[index].addButton({                    id: jxfilePicker,                    label: '继续添加'                });            }                                    //当文件加入队列时触发uploader[0].upload();            uploader[index].onFileQueued = function( file ) {                            fileCount++;                fileSize += file.size;                if ( fileCount === 1 ) {                placeholder.addClass( 'element-invisible' );                    statusBar.show();                }                                addFile( file,uploader[index],queue);                setState( 'ready' ,uploader[index],placeholder,queue,statusBar,jxfilePicker);                updateStatus('ready',info,fileCount,fileSize);            };    //当文件被移除队列后触发。            uploader[index].onFileDequeued = function( file ) {            fileCount--;                fileSize -= file.size;                if ( !fileCount ) {                    setState( 'pedding',uploader[index],placeholder,queue,statusBar,jxfilePicker);                    updateStatus('pedding',info,fileCount,fileSize);                }                              removeFile( file );            };            //上传成功(注意:后台返回值这里可以获取到)           uploader[index].on('uploadSuccess',function(file,reponse){                        layer.alert("上传成功",{offset: '250px',icon:1});            });                        //可以在这里附加额外上传数据                        uploader[index].on('uploadBeforeSend',function(object,data,header) {            /*var tt=$("input[name='id']").val();            data=$.extend(data,{            modelid:tt            });*/            });        });                    // 当有文件添加进来时执行,负责view的创建        function addFile( file,now_uploader,queue) {            var $li = $( '<li id="' + file.id + '">' +                    '<p class="title">' + file.name + '</p>' +                    '<p class="imgWrap"></p>'+                    '<p class="progress"><span></span></p>' +                    '</li>' ),                    $btns = $('<div class="file-panel">' +                            '<span class="cancel">删除</span>' +                            '<span class="rotateRight">向右旋转</span>' +                            '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),                        $prgress = $li.find('p.progress span'),                        $wrap = $li.find( 'p.imgWrap' ),                        $info = $('<p class="error"></p>');                            $wrap.text( '预览中' );            now_uploader.makeThumb( file, function( error, src ) {                if ( error ) {                    $wrap.text( '不能预览' );                    return;                }                var img = $('<img src="'+src+'">');                $wrap.empty().append( img );            }, thumbnailWidth, thumbnailHeight );            percentages[ file.id ] = [ file.size, 0 ];            file.rotation = 0;                      /*            file.on('statuschange', function( cur, prev ) {                if ( prev === 'progress' ) {                    $prgress.hide().width(0);                } else if ( prev === 'queued' ) {                    $li.off( 'mouseenter mouseleave' );                    $btns.remove();                }                // 成功                if ( cur === 'error' || cur === 'invalid' ) {                    console.log( file.statusText );                    showError( file.statusText );                    percentages[ file.id ][ 1 ] = 1;                } else if ( cur === 'interrupt' ) {                    showError( 'interrupt' );                } else if ( cur === 'queued' ) {                    percentages[ file.id ][ 1 ] = 0;                } else if ( cur === 'progress' ) {                    $info.remove();                    $prgress.css('display', 'block');                } else if ( cur === 'complete' ) {                    $li.append( '<span class="success"></span>' );                }                $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );            });            */            $li.on( 'mouseenter', function() {                $btns.stop().animate({height: 30});            });            $li.on( 'mouseleave', function() {                $btns.stop().animate({height: 0});            });                        $btns.on( 'click', 'span', function() {                var index = $(this).index(),                    deg;                switch ( index ) {                    case 0:                    now_uploader.removeFile( file );                        return;                    case 1:                        file.rotation += 90;                        break;                    case 2:                        file.rotation -= 90;                        break;                }                if ( supportTransition ) {                    deg = 'rotate(' + file.rotation + 'deg)';                    $wrap.css({                        '-webkit-transform': deg,                        '-mos-transform': deg,                        '-o-transform': deg,                        'transform': deg                    });                } else {                    $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');                                    }            });            $li.appendTo(queue);        }                // 负责view的销毁        function removeFile( file ) {             //view的显示删除           var $li = $('#'+file.id);            delete percentages[ file.id ];                       $li.off().find('.file-panel').off().end().remove();            //后台删除文件            $.ajax({            url:'deleteFile.do?id='+ file.id,            type:'GET',            async:false,            success:function(result){            var t = eval('('+result+')');            if(t.status == 99){            layer.alert("移除成功!",{icon:1,offset:"200px"});            }else{            layer.alert("移除失败!",{icon:2,offset:"200px"});            }            }            });        } 


回显核心代码

//当文件加入队列时触发uploader[0].upload();            uploader[index].onFileQueued = function( file ) {    fileCount++;                fileSize += file.size;                if ( fileCount === 1 ) {                placeholder.addClass( 'element-invisible' );                    statusBar.show();                }                addFile( file,uploader[index],queue);                setState( 'ready' ,uploader[index],placeholder,queue,statusBar,jxfilePicker);                updateStatus('ready',info,fileCount,fileSize);            };            //加载的时候,页面加载的时候模拟文件加入队列进行图片的编辑回显            uploader[index].on('ready',function(){            var id = $("#id").val();            if(typeof(id) == 'undefined'){            return;            }            $.ajax({            url:'getFiles.do?permissionId=' + id + '&index=' + index,//数据库获取文件信息            type:'GET',            async:false,            success:function(files){            var files = eval('('+files+')');            for(var i = 0; i < files.length; i++){            var obj ={};            statusMap = {};            fileCount++;                            fileSize += files[i].size;                            if ( fileCount === 1 ) {                            placeholder.addClass( 'element-invisible' );                                statusBar.show();                            }                            obj.id=files[i].id;                            obj.name=files[i].name;                            obj.type=files[i].type;                            obj.size=files[i].size;                            obj.ret=files[i].url;                            obj.source=this;                            obj.flog=true;                            obj.status = 'complete',                            obj.getStatus = function(){                            return '';                            }                            obj.version = WebUploader.Base.version;                            obj.statusText = '';                            obj.setStatus = function(){                            var prevStatus = statusMap[this.id];                            typeof text !== 'undefined' && (this.statusText = text);                            if(status !== prevStatus){                            statusMap[this.id] = status;                            //文件状态设置为已完成                            uploader[index].trigger('statuschage',status,prevStatus);                            }                            }                            addFile( obj,uploader[index],queue);                            setState( 'ready' ,uploader[index],placeholder,queue,statusBar,jxfilePicker);                            updateStatus('ready',info,fileCount,fileSize);            }            }            });            });





                                

4 0
原创粉丝点击