jquery(function() {
var $ = jquery, // just in case. make sure it's not an other libaray.
$wrap = $('#uploader'),
// 图片容器
$queue = $('
')
.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,//设备的物理像素和dip的比例
// 缩略图大小
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;
})(),
// webuploader实例
uploader;
if ( !webuploader.uploader.support() ) {
alert( 'web uploader 不支持您的浏览器!如果你使用的是ie浏览器,请尝试升级 flash 播放器');
throw new error( 'webuploader does not support the browser you are using.' );
}
// 实例化
uploader = webuploader.create({
pick: {//指定选择文件的按钮容器
id: '#filepicker',
label: '点击选择图片'
},
dnd: '#uploader .queuelist',//指定drag and drop拖拽的容器,如果不指定,则不启动。
paste: document.body,//指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。
accept: {//指定接受哪些类型的文件
title: 'images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimetypes: 'image/*'
},
sendasbinary:true,//是否以二进制的流的方式发送文件,android 系统的一个bug,只要 文件 blob 修改过后在经过 xhr2 发送出去内容就会变成空,改成二进制的方式发送可以避免这个问题。
// swf文件路径
swf: '/webuploader/js/uploader.swf',
disableglobaldnd: true,// 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
formdata:{//传递的参数
userid:$("#userid").val(),
langid:$("#langid").val()
},
chunked: true,//开启分片
server: '/front/action/3g/savenotebook3gfileaction.do',
filenumlimit: 30,//限制文件上传数
filesizelimit: 150 * 1024 * 1024, //文件总容量限制 150 m
filesinglesizelimit: 5 * 1024 * 1024 //单个文件最大容量 5 m
});
// 添加“添加文件”的按钮,
uploader.addbutton({
id: '#filepicker2',
label: '继续添加'
});
// 当有文件添加进来时执行,负责view的创建
function addfile( file ) {
var $li = $( '' +
'' + file.name + '
' +
''+
'
' +
'' ),
$btns = $('' +
'删除' +
'向右旋转' +
'向左旋转
').appendto( $li ),
$prgress = $li.find('p.progress span'),
$wrap = $li.find( 'p.imgwrap' ),
$info = $(''),
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' ) {//状态是无效的,getstatus():获取文件统计信息
showerror( file.statustext );
} else {
// @todo lazyload
$wrap.text( '预览中' );
//创建缩略图
uploader.makethumb( file, function( error, src ) {
if ( error ) {
$wrap.text( '不能预览' );
return;
}
var img = $('');
$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( '' );
}
$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) +')');
}
});
$li.appendto( $queue );
}//添加文件的方法在此结束
// 负责view的销毁
function removefile( file ) {
var $li = $('#'+file.id);
delete percentages[ file.id ];//删除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 ) + '。';//formatsize:格式化文件大小, 输出成带单位的字符串
} else if ( state === 'confirm' ) {//状态为确认
stats = uploader.getstats();
if ( stats.uploadfailnum ) {
text = '已成功上传' + stats.successnum+ '张照片,'+
stats.uploadfailnum + '张照片上传失败,重新上传失败图片或忽略'
}
} else {
stats = uploader.getstats();
text = '共' + filecount + '张(' +
webuploader.formatsize( filesize ) +
'),已上传' + stats.successnum + '张';
if ( stats.uploadfailnum ) {
text += ',失败' + stats.uploadfailnum + '张';
}
}
$info.html( text );
}
var arr=new array();
//设置状态
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.parent().removeclass('filled');
$queue.hide();
$statusbar.addclass( 'element-invisible' );
uploader.refresh();
break;
case 'ready'://准备上传之前
$placeholder.addclass( 'element-invisible' );//隐藏没选择文件之前的内容
$( '#filepicker2' ).removeclass( 'element-invisible');//显示filepicker2
$queue.parent().addclass('filled');
$queue.show();
$statusbar.removeclass('element-invisible');//显示状态栏
uploader.refresh();
break;
case 'uploading'://上传中
$( '#filepicker2' ).addclass( 'element-invisible' );//隐藏filepicker2
$progress.show();
$upload.text( '暂停上传' );//设置上传按键为暂停上传
break;
case 'paused'://暂停
$progress.show();
$upload.text( '继续上传' );
break;
case 'confirm'://确认
$progress.hide();
$upload.text( '开始上传' ).addclass( 'disabled' );//禁用上传按键
stats = uploader.getstats();//得到状态统计信息
if ( stats.successnum && !stats.uploadfailnum ) {
setstate( 'finish' );//设置状态为完成
return;
}
break;
case 'finish':
stats = uploader.getstats();
if ( stats.successnum ) {
var json={"json":arr}//设为json对象
var data=json.stringify(json);//json对象转为json字符串
document.getelementbyid("upload").value=data;//赋值给隐藏域
// alert( '上传成功' );
$( '#filepicker2' ).removeclass( 'element-invisible');//显示filepicker2
$upload.removeclass( 'disabled' );//移除上传按键的禁用
} 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;
}
});
//当validate不通过时,会以派送错误事件的形式通知调用者。通过upload.on('error', handler)可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
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();
}
});
uploader.on( 'uploadsuccess', function( file, response ) {
//把返回的json对象转为json字符串
arr.push(response);
});
$info.on( 'click', '.retry', function() {
uploader.retry();
} );
$info.on( 'click', '.ignore', function() {
alert( 'todo' );
} );
$upload.addclass( 'state-' + state );
updatetotalprogress();
});