$.fn.uploadrun = function (opt) {
//语言版本
languageopt = {
cn: {
unsupportmsg: '该上传插件不支持您的浏览器!如果您使用的是ie浏览器,请尝试升级 flash 播放器',
browsemsg: '点击选择文件',
keepaddmsg: '继续添加',
allowtypemsg: '支持格式:',
delmsg: '删除',
rightmsg: '向右旋转',
leftmsg: '向左旋转',
overmaxmsg: '文件大小超出',
pausemsg: '上传暂停',
failedmsg: '上传失败,请重试',
previewmsg: '预览中',
notpreviewmsg: '不能预览',
selectedmsg: '选中@0个文件,共@1。',
successmsg: '已成功上传@0,上传失败@1',
countmsg: '共@0张(@1),已上传@2张',
failedcountmsg: ',失败@0张',
stopmsg: '暂停上传',
continuemsg: '继续上传',
startmsg: '开始上传',
q_type_denied: opt.fileextmsg || "请选择支持的文件格式!",
q_exceed_num_limit: "单次只能上传50个文件!",
q_exceed_size_limit: "单次上传的文件总量不能超过 @0kb!",
q_exceed_size: opt.maxsizemsg || "单个文件容量过大,最大 @0kb!",
q_duplicate: "选择了重复文件!",
},
en: {
unsupportmsg: 'webuploader does not support the browser you are using.',
browsemsg: 'browse',
keepaddmsg: 'keep adding',
allowtypemsg: 'allow upload format:',
delmsg: 'delete',
rightmsg: 'rotate right',
leftmsg: 'rotate left',
overmaxmsg: 'file size exceeds maximum',
pausemsg: 'pause',
failedmsg: 'upload failed,please try agains',
previewmsg: 'preview',
notpreviewmsg: "can't preview",
selectedmsg: 'selected @0 files,total @1.',
successmsg: 'success @0,fail@1',
countmsg: 'total @0(@1),success @',
failedcountmsg: ',fail @0',
stopmsg: 'pause',
continuemsg: 'continue',
startmsg: 'start',
q_type_denied: opt.fileextmsg || "please select a supported file format!",
q_exceed_num_limit: "only 50 files can be uploaded at a single time!",
q_exceed_size_limit: "total file uploads cannot exceed @0kb!",
q_exceed_size: opt.maxsizemsg || "the file is too large,maximum @0kb!",
q_duplicate: "duplicate file selected!",
}
};
var $ = jquery,
$wrap = $(opt.fileid),
swfurl = window.location.protocol + '//' + window.location.host + $("script[websiteurl]").attr("websiteurl") + 'res/webuploader/uploader.swf',
uploadurl = window.location.protocol + '//' + window.location.host + $("script[websiteurl]").attr("websiteurl") + 'ajax/whirupload.aspx?formid=' + opt.formid + '&ispic=' + (opt.ispic ? '1' : '0'),
// 图片容器
$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,
//语言版本 cn-中文,en-英文
lang = opt.lang || "cn",
// 优化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;
})(),
// webuploader实例
uploader;
if (!webuploader.uploader.support()) {
alert(languageopt[lang]['unsupportmsg']);
throw new error(languageopt[lang]['unsupportmsg']);
}
// 实例化
uploader = webuploader.create({
pick: {
id: opt.filepicker,
label: languageopt[lang]['browsemsg'],
multiple: opt.ismulti
},
dnd: opt.fileid + ' .queuelist',
paste: document.body,
//上传类型
accept: {
title: 'images',
extensions: opt.fileext ? opt.fileext : 'gif,jpg,jpeg,bmp,png',
mimetypes: opt.ispic ? 'image/*' : ''
},
// swf文件路径
swf: swfurl,
//是否允许拖拽
disableglobaldnd: true,
//分片上传
chunked: true,
//上传文件接收地址
server: uploadurl,
//最多选择文件数量
filenumlimit: 50,
//总文件大小
filesizelimit: opt.size ? opt.size * 20 * 1024 : 200 * 1024 * 1024, // 200 m 文件大小限制
//单个文件大小
filesinglesizelimit: opt.size ? opt.size * 1024 : 5 * 1024 * 1024 // 5 m 单文件大小限制
});
// 添加“添加文件”的按钮,
uploader.addbutton({
id: opt.filepicker2,
label: languageopt[lang]['keepaddmsg']
});
$placeholder.append("" + languageopt[lang]['allowtypemsg'] + opt.fileext + "
");
// 当有文件添加进来时执行,负责view的创建
function addfile(file) {
var $li = $('' +
'' + file.name + '
' +
'' +
'
' +
''),
$btns = $('' +
'' + languageopt[lang]['delmsg'] + '' +
'' + languageopt[lang]['rightmsg'] + '' +
'' + languageopt[lang]['leftmsg'] + '
').appendto($li),
$prgress = $li.find('p.progress span'),
$wrap = $li.find('p.imgwrap'),
$info = $(''),
showerror = function (code) {
switch (code) {
case 'exceed_size':
text = languageopt[lang]['overmaxmsg'];
break;
case 'interrupt':
text = languageopt[lang]['pausemsg'];
break;
default:
text = languageopt[lang]['failedmsg'];
break;
}
$info.text(text).appendto($li);
};
if (file.getstatus() === 'invalid') {
showerror(file.statustext);
} else {
// @todo lazyload
$wrap.text(languageopt[lang]['previewmsg']);
uploader.makethumb(file, function (error, src) {
if (error) {
$wrap.text(languageopt[lang]['notpreviewmsg']);
return;
}
var img = $('');
$wrap.empty().append(img);
}, thumbnailwidth, thumbnailheight);
percentages[file.id] = [file.size, 0];
file.rotation = 0;
$upload.removeclass("disabled");
}
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];
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 = languageopt[lang]['selectedmsg'].replace("@0", filecount).replace("@1", webuploader.formatsize(filesize));
} else if (state === 'confirm') {
stats = uploader.getstats();
if (stats.uploadfailnum) {
text = languageopt[lang]['successmsg'].replace("@0", stats.successnum).replace("@1", stats.uploadfailnum);
}
} else {
stats = uploader.getstats();
text = languageopt[lang]['countmsg'].replace("@0", filecount).replace("@1", webuploader.formatsize(filesize)).replace("@2", stats.successnum);
if (stats.uploadfailnum) {
text = languageopt[lang]['failedcountmsg'].replace("@0", 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.parent().removeclass('filled');
$queue.hide();
$statusbar.addclass('element-invisible');
uploader.refresh();
break;
case 'ready':
$placeholder.addclass('element-invisible');
$(opt.filepicker2).removeclass('element-invisible');
$queue.parent().addclass('filled');
$queue.show();
$statusbar.removeclass('element-invisible');
uploader.refresh();
break;
case 'uploading':
$(opt.filepicker2).addclass('element-invisible');
$progress.show();
$upload.text(languageopt[lang]['stopmsg']);
break;
case 'paused':
$progress.show();
$upload.text(languageopt[lang]['continuemsg']); startmsg
break;
case 'confirm':
$progress.hide();
$upload.text(languageopt[lang]['startmsg']).addclass('disabled');
stats = uploader.getstats();
if (stats.successnum && !stats.uploadfailnum) {
setstate('finish');
return;
}
break;
case 'finish':
$(opt.filepicker2).removeclass('element-invisible');
stats = uploader.getstats();
if (stats.successnum) {
//alert('上传成功');
} 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('uploadsuccess', function (file, response) {
if (response.result) {
// 上传成功
if (opt.ismulti)
$(opt.fileurl).val($(opt.fileurl).val() + "*" + response.msg);
else
$(opt.fileurl).val(response.msg);
} else {
// 上传错误或失败
var $file = $("#" + file.id);
$error = $('');
$error.text(response.msg).appendto($file);
$file.find(".success").remove();
}
});
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) {
switch (code) {
case 'q_type_denied':
alert(languageopt[lang]['q_type_denied']);
break;
case 'q_exceed_num_limit':
alert(languageopt[lang]['q_exceed_num_limit']);
break;
case 'q_exceed_size_limit':
alert(languageopt[lang]['q_exceed_size_limit'].replace("@0", opt.size ? opt.size * 20 : 200));
break;
case 'f_exceed_size':
alert(languageopt[lang]['q_exceed_size'].replace("@0", opt.size ? opt.size : 5));
break;
case 'f_duplicate':
alert(languageopt[lang]['q_duplicate']);
break;
}
};
$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();
/*关闭上传框窗口后恢复上传框初始状态*/
function closeuploader() {
// 移除所有缩略图并将上传文件移出上传序列
for (var i = 0; i < uploader.getfiles().length; i++) {
// 将图片从上传序列移除
uploader.removefile(uploader.getfiles()[i]);
// 将图片从缩略图容器移除
var $li = $('#' + uploader.getfiles()[i].id);
$li.off().remove();
}
setstate('pedding');
// 重置文件总个数和总大小
filecount = 0;
filesize = 0;
// 重置uploader,目前只重置了文件队列
uploader.reset();
// 更新状态等,重新计算文件总个数和总大小
updatestatus();
}
return {
closeuploader: closeuploader,
fileurl: opt.fileurl
}
}