thinkphp整合webuploader的使用 添加以及删除修改

来源:互联网 发布:人事软件有哪些 编辑:程序博客网 时间:2024/05/11 18:39

 上传及修改

      首先是前端部分:

     我是用iframe层打开的上传界面然后在进行添加或修改图集主要代码

add.html:

<input type="button" class="button bg-blue margin-left" id="image1" value="+ 浏览上传" onclick="zpss();"><input type="hidden" id="imgarr" value="" name="imgarr" />     图片路径隐藏域  //打开上传页面  function zpss(){              //iframe层            layer.open({              type: 2,              title: '多图上传',              shadeClose: true,              shade: 0.1,              area: ['40%', '70%'],              content:"{:U('Product/duotu')}" //iframe的url            });           }//上传页面接收iframe层传递回来的图片路径赋给隐藏域添加 function callbacks(imgarr){       if(imgarr != ''){            $("#imgarr").val(imgarr);            $("#yishang").css("display","block");            layer.closeAll();    //添加完成关闭上传层       }    }

iframe页面html:


<!DOCTYPE HTML><html><head><meta charset="utf-8"><title>WebUploader</title><link rel="stylesheet" type="text/css" href="__PUBLIC__/webuploader/0.1.5/webuploader.css" /></head><body><div class="uploader-list-container"> <input type="hidden" class="imgfirst" name="imgfirst">        <div class="queueList">        <div id="dndArea" class="placeholder">            <div id="filePicker-2"></div>        </div>    </div>    <ul>    </ul>    <div class="statusBar" style="display:none;">        <div class="progress"> <span class="text">0%</span> <span class="percentage"></span> </div>        <div class="info"></div>        <div class="btns">            <div id="filePicker2"></div>            <div class="uploadBtn">开始上传</div>        </div>    </div></div><input type="hidden" value="{$ids}" id="ids"><script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript" src="__PUBLIC__/webuploader/0.1.5/webuploader.min.js"></script><script type="text/javascript" >(function( $ ){    // 当domReady的时候开始初始化    $(function() {        var $wrap = $('.uploader-list-container'),            // 图片容器            $queue = $( '<ul class="filelist"></ul>' )                .appendTo( $wrap.find( '.queueList' ) ),            // 状态栏,包括进度和控制按钮            $statusBar = $wrap.find( '.statusBar' ),            // 文件总体选择信息。            $info = $statusBar.find( '.info' ),            // 上传按钮            $upload = $wrap.find( '.uploadBtn' ),            // 没选择文件之前的内容。            $placeHolder = $wrap.find( '.placeholder' ),            $progress = $statusBar.find( '.progress' ).hide(),            // 添加的文件数量            fileCount = 0,            // 添加的文件总大小            fileSize = 0,            // 优化retina, 在retina下这个值是2            ratio = window.devicePixelRatio || 1,            // 缩略图大小            thumbnailWidth = 110 * ratio,            thumbnailHeight = 110 * ratio,            // 可能有pedding, ready, uploading, confirm, done.            state = 'pedding',            // 所有文件的进度信息,key为file id            percentages = {},            // 判断浏览器是否支持图片的base64            isSupportBase64 = ( function() {                var data = new Image();                var support = true;                data.onload = data.onerror = function() {                    if( this.width != 1 || this.height != 1 ) {                        support = false;                    }                }                data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";                return support;            } )(),            // 检测是否已经安装flash,检测flash的版本            flashVersion = ( function() {                var version;                try {                    version = navigator.plugins[ 'Shockwave Flash' ];                    version = version.description;                } catch ( ex ) {                    try {                        version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')                                .GetVariable('$version');                    } catch ( ex2 ) {                        version = '0.0';                    }                }                version = version.match( /\d+/g );                return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );            } )(),            supportTransition = (function(){                var s = document.createElement('p').style,                    r = 'transition' in s ||                            'WebkitTransition' in s ||                            'MozTransition' in s ||                            'msTransition' in s ||                            'OTransition' in s;                s = null;                return r;            })(),            // WebUploader实例            uploader;        // 实例化        uploader = WebUploader.create({            pick: {                id: '#filePicker-2',                label: '点击选择图片'            },            formData: {                uid: 123            },            dnd: '#dndArea',            paste: '#uploader',            swf: '../Uploader.swf',            chunked: false,            chunkSize: 512 * 1024,            server: '{:U("Product/duotu_add")}',            // runtimeOrder: 'flash',            // accept: {            //     title: 'Images',            //     extensions: 'gif,jpg,jpeg,bmp,png',            //     mimeTypes: 'image/*'            // },            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。            disableGlobalDnd: true,            fileNumLimit: 300,            fileSizeLimit: 200 * 1024 * 1024,    // 200 M            fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M        });
 //编辑已上传照片信息----------------------------------------------------------------------------------------------

var ids = $("#ids").val();


if(ids != ''){
    
      
            uploader.on('ready', function() {
                $statusBar.show(); //显示新增和上传按钮
                setState( 'ready' ); //重置上传按钮状态
                //载入现有照片

        $li = $('<volist name="imgarr" id="vo">'+'<li id="{$key}" title ="{$vo}">'+
        '<img src="__ROOT__{$vo}"></li>'+'</volist>');
                //给li添加删除按钮
                $btns = $('<div class="file-panel" style="height: 25px;">' +
                        '<span class="cancel">删除</span>' +
                        '<b class="ysc">已上传</b></div>').appendTo( $li );
                $(".filelist").append( $li );
                //点击删除,提交给控制器进行删除操作     
                $(".cancel ").click(function(){

                    var imgid = $("#duotu_add")

                     //定义传给控制器的文件URL和照片ID
                    var urlValue = '.' + $(this).closest('li').attr('title');
                    var idValue =  $(this).closest('li').attr('id');
                    var ids = $("#ids").val();
删除方法------------------------------------------------------------------------------------------------------------
                      //提交到控制器
                    $.post('{:U("Product/delfile")}',{'url':urlValue,'id':idValue,'ids':ids},function(data){
                      
                      if(data.code == 200){
                        
                        //如删除成功,移除这个li
                        $("#"+idValue).remove();

                         alert(data.msg);

                      }else{

                         alert(data.msg);
                      }
                    });
                });
             });
}



        // 拖拽时不接受 js, txt 文件。
        uploader.on( 'dndAccept', function( items ) {
            var denied = false,
                len = items.length,
                i = 0,
                // 修改js类型
                unAllowed = 'text/plain;application/javascript ';

            for ( ; i < len; i++ ) {
                // 如果在列表里面
                if ( ~unAllowed.indexOf( items[ i ].type ) ) {
                    denied = true;
                    break;
                }
            }

            return !denied;
        });


          //ajax 成功返回地址
         var arr    =  [ ]; //定义全局数组
         uploader.on('uploadSuccess',function(file,response){
            var imgurl = response; //上传图片的路径
            $(".imgfirst").each(function(){  //使用foreach 循环 地址
               arr.push(imgurl);   //地址追加进数组
            });
            $(".imgfirst").val(arr); //将地址写入到form表单
         });




        uploader.on('dialogOpen', function() {
            console.log('here');
        });


        // 添加“添加文件”的按钮,
        uploader.addButton({
            id: '#filePicker2',
            label: '继续添加'
        });

        uploader.on('ready', function() {
            window.uploader = uploader;
        });

        // 当有文件添加进来时执行,负责view的创建
        function addFile( file ) {

             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>'),

                showError = function( code ) {
                    switch( code ) {
                        case 'exceed_size':
                            text = '文件大小超出';
                            break;

                        case 'interrupt':
                            text = '上传暂停';
                            break;

                        default:
                            text = '上传失败,请重试';
                            break;
                    }

                    $info.text( text ).appendTo( $li );
                };

            if ( file.getStatus() === 'invalid' ) {
                showError( file.statusText );
            } else {
                // @todo lazyload
                $wrap.text( '预览中' );
                uploader.makeThumb( file, function( error, src ) {
                    var img;

                    if ( error ) {
                        $wrap.text( '不能预览' );
                        return;
                    }

                    if( isSupportBase64 ) {
                        img = $('<img src="'+src+'">');
                        $wrap.empty().append( img );
                    } else {
                        $.ajax('../server/preview.php', {
                            method: 'POST',
                            data: src,
                            dataType:'json'
                        }).done(function( response ) {
                            if (response.result) {
                                img = $('<img src="'+response.result+'">');
                                $wrap.empty().append( img );
                            } else {
                                $wrap.text("预览出错");
                            }
                        });
                    }
                }, 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:
                        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) +')');
                    // use jquery animate to rotation
                    // $({
                    //     rotation: rotation
                    // }).animate({
                    //     rotation: file.rotation
                    // }, {
                    //     easing: 'linear',
                    //     step: function( now ) {
                    //         now = now * Math.PI / 180;

                    //         var cos = Math.cos( now ),
                    //             sin = Math.sin( now );

                    //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
                    //     }
                    // });
                }


            });

            $li.appendTo( $queue );
        }

        // 负责view的销毁
        function removeFile( file ) {
            var $li = $('#'+file.id);

            delete percentages[ file.id ];
            updateTotalProgress();
            $li.off().find('.file-panel').off().end().remove();
        }

        function updateTotalProgress() {
            var loaded = 0,
                total = 0,
                spans = $progress.children(),
                percent;

            $.each( percentages, function( k, v ) {
                total += v[ 0 ];
                loaded += v[ 0 ] * v[ 1 ];
            } );

            percent = total ? loaded / total : 0;


            spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
            spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
            updateStatus();
        }

        function updateStatus() {
            var text = '', stats;

            if ( state === 'ready' ) {
                text = '选中' + fileCount + '张图片,共' +
                        WebUploader.formatSize( fileSize ) + '。';
            } else if ( state === 'confirm' ) {
                stats = uploader.getStats();
                if ( stats.uploadFailNum ) {
                    text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+
                        stats.uploadFailNum + '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                }

            } else {
                stats = uploader.getStats();
                text = '共' + fileCount + '张(' +
                        WebUploader.formatSize( fileSize )  +
                        '),已上传' + stats.successNum + '张';

                if ( stats.uploadFailNum ) {
                    text += ',失败' + stats.uploadFailNum + '张';
                }
            }

            $info.html( text );
        }
      

        function setState( val ) {
            var file, stats;

            if ( val === state ) {
                return;
            }

            $upload.removeClass( 'state-' + state );
            $upload.addClass( 'state-' + val );
            state = val;

            switch ( state ) {
                case 'pedding':
                    $placeHolder.removeClass( 'element-invisible' );
                    $queue.hide();
                    $statusBar.addClass( 'element-invisible' );
                    uploader.refresh();
                    break;

                case 'ready':
                    $placeHolder.addClass( 'element-invisible' );
                    $( '#filePicker2' ).removeClass( 'element-invisible');
                    $queue.show();
                    $statusBar.removeClass('element-invisible');
                    uploader.refresh();
                    break;

                case 'uploading':
                    $( '#filePicker2' ).addClass( 'element-invisible' );
                    $progress.show();
                    $upload.text( '暂停上传' );
                    break;

                case 'paused':
                    $progress.show();
                    $upload.text( '继续上传' );
                    break;

                case 'confirm':
                    $progress.hide();
                    $( '#filePicker2' ).removeClass( 'element-invisible' );
                    $upload.text( '开始上传' );

                    stats = uploader.getStats();
                    if ( stats.successNum && !stats.uploadFailNum ) {
                        setState( 'finish' );
                        return;
                    }
                    break;
                case 'finish':
                    stats = uploader.getStats();
                    if ( stats.successNum ) {
                        alert( '上传成功' );
上传成功----------------------------------------------------------------------------------------------------------

                                //取得上传所有的图片路径返回给父页面的callbacks方法
                       var imgarr = $('.imgfirst').val();

                         parent.callbacks(imgarr);
                            
                     } else {
                        // 没有成功的图片,重设
                        state = 'done';
                        location.reload();
                    }
                    break;
            }

            updateStatus();
        }

        uploader.onUploadProgress = function( file, percentage ) {
            var $li = $('#'+file.id),
                $percent = $li.find('.progress span');

            $percent.css( 'width', percentage * 100 + '%' );
            percentages[ file.id ][ 1 ] = percentage;
            updateTotalProgress();
        };

        uploader.onFileQueued = function( file ) {
            fileCount++;
            fileSize += file.size;

            if ( fileCount === 1 ) {
                $placeHolder.addClass( 'element-invisible' );
                $statusBar.show();
            }

            addFile( file );
            setState( 'ready' );
            updateTotalProgress();
        };

        uploader.onFileDequeued = function( file ) {
            fileCount--;
            fileSize -= file.size;

            if ( !fileCount ) {
                setState( 'pedding' );
            }

            removeFile( file );
            updateTotalProgress();

        };

        uploader.on( 'all', function( type ) {
            var stats;
            switch( type ) {
                case 'uploadFinished':
                    setState( 'confirm' );
                    break;

                case 'startUpload':
                    setState( 'uploading' );
                    break;

                case 'stopUpload':
                    setState( 'paused' );
                    break;

            }
        });

        uploader.onError = function( code ) {
            alert( 'Eroor: ' + code );
        };

        $upload.on('click', function() {
            if ( $(this).hasClass( 'disabled' ) ) {
                return false;
            }

            if ( state === 'ready' ) {
                uploader.upload();
            } else if ( state === 'paused' ) {
                uploader.upload();
            } else if ( state === 'uploading' ) {
                uploader.stop();
            }
        });

        $info.on( 'click', '.retry', function() {
            uploader.retry();
        } );

        $info.on( 'click', '.ignore', function() {
            alert( 'todo' );
        } );

        $upload.addClass( 'state-' + state );
        updateTotalProgress();
    });

})( jQuery );

</script>

</body>
</html>

edit.html:

修改页面隐藏域:    <input type="hidden" id="imgarr" value="" name="imgarr" />

后台控制器:

    //多图页面显示    public function duotu(){                  if(IS_GET){                $ids = I('get.id');                $val = M('chanping')->where("`id`='$ids'")->find();                                  $imgarr = $val['imgarr'];                $new_arr = explode(',', $imgarr);     //取得所有图                $this->assign("imgarr",$new_arr);                $this->assign("ids",$ids);                        }          $this->display();    }       //多图文件上传并返回路径    public function duotu_add(){          $config = array(              'mimes'  =>  array(), //允许上传的文件MiMe类型              'maxSize' =>  0, //上传的文件大小限制 (0-不做限制)              'exts'   =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀              'autoSub' =>  true, //自动子目录保存文件              'subName' =>  array('date', 'Y-m-d'), //子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组              'rootPath' =>  './Uploads/', //保存根路径              'savePath' =>  '',//保存路径                        );          $upload = new \Think\Upload($config);// 实例化上传类                               $info   =   $upload->upload();          // dump($info);die;                            if(!$info) {                         $this->error($upload->getError());// 上传错误提示错误信息                       }else{// 上传成功                     // dump($info);die;            foreach ($info as $k=>$va){                             $tus .= "/Uploads/".$va['savepath'].$va['savename'];               $this->ajaxReturn($tus);            }       }    }                 //修改多图    public function delfile(){         if(IS_AJAX){            $url = I('post.url');            $ids = I('post.id');            $id = I('post.ids');            $result = unlink($url);            if ($result == true) {                    $res = M('chanping')->where("`id`= $id")->find();                    $imgarr = explode(',', $res['imgarr']);   //获取图集                    array_splice($imgarr, $ids,1);   //删除指定图片                    $data['imgarr'] = implode(",", $imgarr);  //分割成新的字符串                    $result = M('chanping')->where("`id`=$id")->save($data);  //更新数据                    $this->ajaxReturn(array('code'=>200,'msg'=>'删除成功'));die;                                 }else                     $this->ajaxReturn(array('code'=>0,'msg'=>'删除失败,请刷新页面'));         }    }   //在修改的时候同时可以继续上传    后台控制器数据更新控制器                              $img = I('post.imgarr');   //接受隐藏域数据,判断有没有新图片上传                $old = M('chanping')->where("id = $id")->field('imgarr')->find();  //查老数据                if(!empty($img)){   如果不为空则为传新图片了                    $pho = $old['imgarr'];   //取得字符串路径                    $img_old = explode(',',$pho);  之前上传的那些图片                    $new_pho = explode(',',$img);  新上传的图片                    $img_new = array_merge($img_old,$new_pho);   合并成新数组                    $data['imgarr'] = implode(',',$img_new);   数组用逗号分隔为新字符串更新                }else{                    $data['imgarr'] = $old['imgarr'];      没有新图上传,图片还为之前的数据                }




  



   

阅读全文
0 0
原创粉丝点击