webuploder根据官方DEMO修改,动态多实例图片上传(含编辑显示图片)

封装的官方实例对,这里无需改动什么,写在自己封装的 webUploaderImage.js 文件中
jQuery(function() {
封装对象自定义传参

var $WebUploadImage = function(uploadPel,directory,filePicker,filePicker2) {
	//保存上传后图片返回的文件路径
	this.url=uploadPel+"Url";
	// 添加的文件数量
    this.fileCount = 0;
    this.filePicker=filePicker;
    this.filePicker2=filePicker2;
    this.uploadPel=uploadPel;
    this.$wrap = $("#"+uploadPel);
    this.$queue=$('<ul class="filelist"></ul>')
        .appendTo( this.$wrap.find('.queueList') );
    this.$statusBar= this.$wrap.find('.statusBar');
    this.$info=this.$statusBar.find('.info');
    this.$upload=this.$wrap.find('.uploadBtn');
    this.$placeHolder=this.$wrap.find('.placeholder');
    this.$progress=this.$statusBar.find('.progress').hide();

    this.uploadUrl = Feng.ctxPath + '/file/upload';
    this.fileSizeLimit = 100 * 1024 * 1024;
    this.picWidth = 800;
    this.picHeight = 800;
    this.uploadBarId = null; // 进度条ID'
    this.directory=directory;
    this.imagePath="";
    this.$li={};
};

var $ = jQuery,    // just in case. Make sure it's not an other libaray.


    // 添加的文件总大小
    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 = {},

    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;
    })();



if ( !WebUploader.Uploader.support() ) {
    alert( 'Web Uploader 不支持您的浏览器!如果你使用的是IE浏览器,请尝试升级 flash 播放器');
    throw new Error( 'WebUploader does not support the browser you are using.' );
}

 $WebUploadImage.prototype={
     uploader:{},
     init : function() {
     	this.uploader = this.create();
		this.bindEvent(this.uploader);
        this.updateTotalProgress();
        this.$upload.addClass( 'state-' + state );
        return this.uploader;
	},
     bindEvent:function(uploader){
     	 var me=this;
         uploader.on('uploadSuccess', function(file,response) {
             if(response.code == 200) {
                 $("#" + me.url).val($("#" + me.url).val()+response.data+",");
                 me.imagePath=response.data;
                 var inp="<input type='hidden' name='imagePath' value="+me.imagePath+"/>";
                 me.$li.append(inp);
             } else {
                 Feng.error(response.message);
             }
         });
         uploader.on( 'all', function( type ) {
             var stats;
             switch( type ) {
                 case 'uploadFinished':
                     me.setState( 'confirm' );
                     break;

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

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

             }
         });

         uploader.onError = function( code ) {
             alert( 'Eroor: ' + code );
         };
         this.$info.on( 'click', '.retry', function() {
             uploader.retry();
         } );

         this.$info.on( 'click', '.ignore', function() {
             alert( 'todo' );
         } );
         this.$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();
             }
         });
         uploader.onFileQueued = function( file ) {
             me.fileCount++;
             fileSize += file.size;

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

             me.addFile( file );
             me.setState( 'ready' );
             me.updateTotalProgress();
         };
         uploader.onFileDequeued = function( file ) {
             me.fileCount--;
             fileSize -= file.size;

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

             me.removeFile( file );
             me.updateTotalProgress();
         };

         // 添加“添加文件”的按钮,
         uploader.addButton({
             id: '#'+me.filePicker2,
             label: '继续添加'
         });
         uploader.onUploadProgress = function( file, percentage ) {
             var $li = $('#'+file.id),
                 $percent = $li.find('.progress span');
             me.$li=$li;
             $percent.css( 'width', percentage * 100 + '%' );
             percentages[ file.id ][ 1 ] = percentage;
             me.updateTotalProgress();
         }
	 },

     setFileQueuedFun:function(file){
         this.fileCount++;
         fileSize += file.size;

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

         this.addFile( file );
         this.setState( 'ready' );
         this.updateTotalProgress();
	 },
	 setAddFiles:function(file){
		this.uploader.addFiles(file);
	 },
     // 实例化
	 create:function(){
         var csrfToken = $("meta[name='_csrf']",top.document).attr("content");
         var csrfHeader = $("meta[name='_csrf_header']",top.document).attr("content");
         var headers = {}; if(csrfToken && csrfHeader)  headers[ csrfHeader ] = csrfToken;
         var webUploader =WebUploader.create({
			 	 // auto : true,
             	 fileVal: "files",
                 pick: {
                     id: '#'+this.filePicker,
                     label: '点击选择图片'
                 },
                 dnd: '#'+this.uploadPel+' .queueList',
                 paste: document.body,

                 accept: {
                     title: 'Images',
                     extensions: 'gif,jpg,jpeg,bmp,png',
                     mimeTypes: 'image/*'
                 },

                 // swf文件路径
                 swf: Feng.ctxPath + '/static/js/plugins/webuploader/Uploader.swf',
			 	 headers: headers,
                 disableGlobalDnd: true,
			     formData: {"directory" :this.directory==null?"headImage":this.directory}, // 文件上传请求的参数表
                 chunked: true,
                 server: this.uploadUrl,
                 // server: 'http://2betop.net/fileupload.php',
                 fileNumLimit: 300,
                 fileSizeLimit: 5 * 1024 * 1024,    // 200 M
                 fileSingleSizeLimit: 1 * 1024 * 1024,    // 50 M,
             });
         return webUploader;
	 },
	 showImg:function(images){
            for(var m in images){
            	if(images[m]==""){
            		continue;
				}
                this.fileCount++;

                if ( this.fileCount === 1 ) {
                    this.$placeHolder.addClass( 'element-invisible' );
                    this.$statusBar.show();
                }
                this.setState( 'ready' );
                var $li = $( '<li id=>' +
                    '<p class="title"></p>' +
                    '<p class="imgWrap"></p>'+
                    '<p class="progress"><span></span></p>' +
                    '</li>' ),
                    $btns = $('<div class="file-panel">' +
                        '<span class="cancel">删除</span></div>').appendTo( $li ),
                    $prgress = $li.find('p.progress span'),
                    $wrap = $li.find( 'p.imgWrap' );
                    // $info = $('<p class="error"></p>');
                // $info.text( text ).appendTo( $li );
                // @todo lazyload
                $wrap.text( '预览中' );
                var img = $('<img src="'+Feng.ctxPath+'/file/download?path='+images[m]+'">');
                $wrap.empty().append( img );
                $li.appendTo( this.$queue );
                $li.append("<input type='hidden' value="+images[m]+" name='imagePath'/>");
                this.addFileBindEvent($li,$btns);
            }
	 },
     // 当有文件添加进来时执行,负责view的创建
     addFile:function( file ) {
     	var text="";
        var me =this;
		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></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 );
			};
		this.addFileBindEvent($li,$btns,file);
		if ( file.getStatus() === 'invalid' ) {
			showError( file.statusText );
		} else {
			// @todo lazyload
			$wrap.text( '预览中' );
			this.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;
		}
         if ( supportTransition ) {
             deg = 'rotate(' + file.rotation + 'deg)';
             me.$wrap.css({
                 '-webkit-transform': deg,
                 '-mos-transform': deg,
                 '-o-transform': deg,
                 'transform': deg
             });
         } else {
             me.$wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
         }
         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.appendTo( me.$queue );
	},
	 addFileBindEvent:function($li,$btns,file){
         var me=this;
         $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;
             if(file){
                 switch ( index ) {
                     case 0:
                         me.uploader.removeFile( file );
                         return;

                     case 1:
                         file.rotation += 90;
                         break;

                     case 2:
                         file.rotation -= 90;
                         break;
                 }
			 }else{
				//判断是不是最后一张图
				 console.log("这是第几张图"+me.fileCount)
                 me.fileCount--;
                 if(me.fileCount==0){
                     //清除文件
                     me.$queue.empty();
                     me.$placeHolder.removeClass( 'element-invisible' );
                     me.$queue.parent().removeClass('filled');
                     me.$queue.hide();
                     me.$statusBar.addClass( 'element-invisible' );
                     me.uploader.refresh();
                 }else{
                    $(this).parents("li").remove();
                 }
             }
             //删除图片同时也更新图片路径
             var path = $(this).parents("li").find("input[name='imagePath']").val();
             me.updateImagePath(path);
         });
	 },
     updateImagePath:function(path){
         var urls = $("#" + this.url).val().split(",");
         urls.splice($.inArray(path,urls),1);
         urls.join(",");
         $("#" + this.url).val(urls)
     },
     setState:function( val ) {
		var file, stats;
		// if ( val === state ) {
		// 	return;
		// }

		this.$upload.removeClass( 'state-' + state );
		this.$upload.addClass( 'state-' + val );
		state = val;
		switch ( state ) {
			case 'pedding':
				this.$placeHolder.removeClass( 'element-invisible' );
				this.$queue.parent().removeClass('filled');
				this.$queue.hide();
				this.$statusBar.addClass( 'element-invisible' );
				this.uploader.refresh();
				break;

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

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

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

			case 'confirm':
				this.$progress.hide();
				this.$upload.text( '开始上传' +
					'' ).addClass( 'disabled' );

				stats = this.uploader.getStats()
				if ( stats.successNum && !stats.uploadFailNum ) {
					this.setState( 'finish' );
					return;
				}
				break;
			case 'finish':
				stats = this.uploader.getStats()
				if ( stats.successNum ) {
					alert( '上传成功' );
				} else {
					// 没有成功的图片,重设
					state = 'done';
					location.reload();
				}
				break;
		}

		this.updateStatus();
	},

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

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

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

		this.$info.html( text );
	},
   updateTotalProgress: function () {
		var loaded = 0,
			total = 0,
			spans = this.$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 ) + '%' );
		this.updateStatus();
	},

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

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

};
window.$WebUploadImage = $WebUploadImage;
});

HML代码

<div id="uploader" class="wu-example uploader">
                            <div class="queueList">
                                <input type="hidden" value=""  name="productImages" id="uploaderUrl"/>
                                <div id="dndArea" class="placeholder">
                                    <div id="filePicker" class="webuploader-container"><div class="webuploader-pick">点击选择图片</div><div  style="position: absolute; top: 0px; left: 448px; width: 168px; height: 44px; overflow: hidden; bottom: auto; right: auto;"><input type="file" name="file" class="webuploader-element-invisible" multiple="multiple" accept="image/*"><label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></div>
                                    <p>或将照片拖到这里,最多可选8张</p>
                                </div>
                                <ul class="filelist" style="display: none;"></ul></div>
                            <div class="statusBar element-invisible" style="">
                                <div class="progress" style="display: none;">
                                    <span class="text">0%</span>
                                    <span class="percentage" style="width: 0%;"></span>
                                </div><div class="info">共0张(0B),已上传0张</div>
                                <div class="btns">
                                    <div id="filePicker2" class="filePicker2 webuploader-container"><div class="webuploader-pick">继续添加</div><div  style="position: absolute; top: 0px; left: 10px; width: 94px; height: 42px; overflow: hidden; bottom: auto; right: auto;"><input type="file" name="file" class="webuploader-element-invisible" multiple="multiple" accept="image/*"><label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></div><div class="uploadBtn state-pedding">开始上传</div>
                                </div>
                            </div>
                        </div>

页面 JS代码
实例化文件上传对象webUploader
var webuploder= new $WebUploadImage(“uploader”,“family/product”,“filePicker”,“filePicker2”);
调用封装好的初始化方法
webuploder.init();
/**
*如果要编辑回显图片就调用此方法
/*后台获取图片路径集合,图片集合就不写了,就是个字符串数组对象
addImagePath(webuploder,picList,“uploader”);
编辑图片回显
function addImagePath(uploader,listPath,imageId) {
var urls= “”;
for(var l in listPath) {
urls+=listPath[l]+",";
}
$("#"+imageId+“Url”).val(urls);
//引入刚刚封装好的webUploaderImage.js文件
uploader.showImg(listPath);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值