jQuery.fn.fileUploadUIX = function(method) {
'use strict';
// under windows, if wps is installed, word file will be taken as application/kswps or application/kset for excel
var docTypes = /^application\/(msword|excel|x-excel|x-msexcel|vnd\.ms-excel|vnd\.openxmlformats-officedocument\.wordprocessingml\.document|vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet|pdf|x-mht|kswps|kset)|vnd.oasis.opendocument.text|vnd.oasis.opendocument.spreadsheet|text\/richtext|text\/plain|text\/html|multipart\/related|message\/rfc822/i;
var imageTypes = /^image\/(gif|bmp|jpeg|png|svg+xml)$/i;
var docImageTypes = /^application\/(msword|vnd\.ms-office|pdf|vnd\.openxmlformats-officedocument\.wordprocessingml\.document|vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet|vnd\.oasis\.opendocument\.text|vnd\.oasis\.opendocument\.spreadsheet|kswps|kset)|image\/(jpeg|png)/i;
var officeTypes = /^application\/(msword|vnd\.ms-office|pdf|vnd\.openxmlformats-officedocument\.wordprocessingml\.document|vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet|vnd\.oasis\.opendocument\.text|vnd\.oasis\.opendocument\.spreadsheet|kswps|kset)|image\/(jpeg)/i;
var compressTypes = /^application\/(zip|octet-stream)$/i;
//for IE only
var validImageFileExts = ["bmp","gif","png","jpg","jpeg"];
var validDocFileExts = ["docx","doc","pdf","odf","rtf","mht","txt","htm","html"];
var validDocImageFileExts = ["png","jpg","jpeg","docx","doc","pdf"];
var validOfficeFileExts = ["jpg","jpeg","docx","doc","pdf"];
var validCompressFileExts = ["zip"];
// map from type => ext
var mimeTypeExtMap = {
imageTypes: [imageTypes, validImageFileExts],
docTypes: [docTypes, validDocFileExts],
docImageTypes: [docImageTypes, validDocImageFileExts],
officeTypes: [officeTypes, validOfficeFileExts],
compressTypes: [compressTypes, validCompressFileExts]
};
// Emulate jQuery UI button (without states) if not available:
if (typeof jQuery().button !== 'function') {
jQuery.fn.button = function (options) {
return this.each(function () {
if (options === 'destroy') {
jQuery(this).removeClass(
'ui-button ui-widget ui-state-default ui-corner-all' +
' ui-button-icon-only ui-button-text-icon-primary'
).html(jQuery(this).text());
} else {
jQuery(this)
.addClass('ui-button ui-widget ui-state-default ui-corner-all')
.addClass(
options.text === false ? 'ui-button-icon-only' :
'ui-button-text-icon-primary'
)
.html(jQuery('<span class="ui-button-text"/>').text(jQuery(this).text()))
.prepend(
jQuery('<span class="ui-button-icon-primary ui-icon"/>')
.addClass(options.icons.primary)
);
}
});
};
}
var UploadHandler = function (container, options) {
var uploadHandler = this;
this.locale = {};
this.sequentialUploads = true;
this.maxFileSize = null;
this.minFileSize = 1;
this.maxNumberOfFiles = null;
this.acceptFileTypes = /.+$/i;
this.acceptFileExts = jQuery.merge(jQuery.merge([], validImageFileExts), validDocFileExts),
this.autoUpload = false;
this.url = container.find('form:first').attr('action');
this.dropZone = container.find('form:first');
this.uploadTable = container.find('.files:first');
this.progressAllNode = container.find('.file_upload_overall_progress div:first');
this.uploadTemplate = this.uploadTable.find('.file_upload_template:first');
this.multiButtons = container.find('.file_upload_buttons:first');
/* based on option, change allow type */
if(options.allowDocType) {
this.acceptFileTypes = docTypes;
this.acceptFileExts = validDocFileExts;
} else if(options.allowImageType) {
this.acceptFileTypes = imageTypes;
this.acceptFileExts = validImageFileExts;
} else if (options.allowDocImageType) {
this.acceptFileTypes = docImageTypes;
this.acceptFileExts = validDocImageFileExts;
} else if (options.allowOfficeTypes) {
this.acceptFileTypes = officeTypes;
this.acceptFileExts = validOfficeFileExts;
};
if(options.mixedFileTypes) {
var self = this;
this.acceptFileExts = [];
this.acceptFileTypes = [];
// allow mixed types is array
$.each(options.mixedFileTypes, function(i, t) {
var typeExt = mimeTypeExtMap[t];
self.acceptFileTypes[self.acceptFileTypes.length++] = typeExt.shift();
$.merge(self.acceptFileExts, typeExt.shift());
});
}
this.adjustMaxNumberOfFiles = function (operand) {
var number = container.fileUploadUIX('option', 'maxNumberOfFiles');
if (typeof number === 'number') {
container.fileUploadUIX('option', 'maxNumberOfFiles', number + operand);
}
};
this.formatFileSize = function (bytes) {
if (typeof bytes !== 'number' || bytes === null) {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
};
this.formatFileName = function (name) {
return name.replace(/^.*[\/\\]/, '');
};
this.enableDragToDesktop = function () {
var link = jQuery(this),
url = link.get(0).href,
name = decodeURIComponent(url.split('/').pop()).replace(/:/g, '-'),
type = 'application/octet-stream';
link.bind('dragstart', function (event) {
try {
event.originalEvent.dataTransfer
.setData('DownloadURL', [type, name, url].join(':'));
} catch (e) {}
});
};
this.buildMultiUploadRow = function (files, handler) {
var rows = jQuery('<tbody style="display:none;"/>');
jQuery.each(files, function (index, file) {
var row = handler.buildUploadRow(files, index, handler).show(),
cells = row.find(
'.file_upload_progress, .file_upload_start, .file_upload_cancel'
);
if (index) {
cells.remove();
} else {
cells.attr('rowspan', files.length);
}
rows.append(row);
});
return rows;
};
this.buildUploadRow = function (files, index, handler) {
if (typeof index !== 'number') {
return handler.buildMultiUploadRow(files, handler);
}
var file = files[index],
fileName = handler.formatFileName(file.name),
uploadRow = handler.uploadTemplate
.clone().removeAttr('id');
uploadRow.find('.file_name')
.text(fileName);
uploadRow.find('.file_size')
.text(handler.formatFileSize(file.size));
uploadRow.find('.file_upload_start').addClass('active');
if (handler.autoUpload) {
uploadRow.find('.file_upload_start button').hide();
} else {
uploadRow.find('.file_upload_start button')
.button();
}
uploadRow.find('.file_upload_cancel button')
.button();
return uploadRow;
};
this.getFileUrl = function (file, handler) {
return file.url;
};
this.getThumbnailUrl = function (file, handler) {
return file.thumbnail;
};
this.onError = function (event, files, index, xhr, handler) {
handler.uploadRow.addClass('file_upload_error')
.find('.file_upload_progress').append(jQuery('<div class="error"/>').append(
handler.locale[event] || event
));
// for autoUpload case the uploadRow has already been removed. re-added again
if(handler.autoUpload) {
var p = handler.uploadRow.appendTo(handler.uploadTable).fadeIn();
p.find('.file_upload_cancel button').button()
.bind('click', function() { handler.removeNode(p, null);});
p.find('.file_upload_progress div:first').hide();
}
};
this.validate = function (event, files, index, xhr, handler) {
var isValid = true,
file;
if (typeof index !== 'number') {
jQuery.each(files, function (index, file) {
isValid = handler.validate(event, files, index, xhr, handler);
});
} else {
file = files[index];
if (handler.maxFileSize && file.size > handler.maxFileSize) {
handler.onError('文件太大。', files, index, xhr, handler);
return false;
} else if (typeof file.size === 'number' && file.size < handler.minFileSize) {
handler.onError('文件太小。', files, index, xhr, handler);
return false;
}
if (jQuery.browser.msie && jQuery.browser.version <= 9) {
var ext=file.name.substring(file.name.lastIndexOf(".")+1,file.name.length).toLowerCase();
if(jQuery.inArray(ext, handler.acceptFileExts) < 0) {
handler.onError('不正确的文件格式。', files, index, xhr, handler);
return false;
}
}
else if (file.type.length <= 0) {
var ext=file.name.substring(file.name.lastIndexOf(".")+1,file.name.length).toLowerCase();
if(jQuery.inArray(ext, handler.acceptFileExts) < 0) {
handler.onError('不正确的文件格式。', files, index, xhr, handler);
return false;
}
}
else {
if($.isArray(handler.acceptFileTypes)) {
var accepted = true;
$.each(handler.acceptFileTypes, function(i, r) {
if(r.test(file.type))
isValid = true;
return isValid;
});
if(!isValid){
handler.onError('不正确的文件格式。', files, index, xhr, handler);
return false;
}
} else if ( !handler.acceptFileTypes.test(file.type) ) {
handler.onError('不正确的文件格式。', files, index, xhr, handler);
return false;
}
}
if (typeof handler.maxNumberOfFiles === 'number' &&
handler.maxNumberOfFiles < index + 1) {
handler.onError('上传太多,已达上限。', files, index, xhr, handler);
return false;
}
}
return isValid;
};
this.uploadCallBack = function (event, files, index, xhr, handler, callBack) {
callBack();
};
this.beforeSend = function (event, files, index, xhr, handler, callBack) {
if (!handler.validate(event, files, index, xhr, handler)) {
handler.uploadRow.find(handler.cancelSelector).click(function (e) {
handler.uploadRow.fadeOut().remove();
});
return;
}
uploadHandler.multiButtons.show();
if(options.captcha) {
jQuery(options.captcha.form).find(".error").html('');
jQuery(options.captcha.form).find("#captcha_code").val('');
jQuery(options.captcha.form).fadeIn();
if(uploadHandler.captcha_checked == true) {
uploadHandler.captcha_checked = null;
jQuery(options.captcha.form).find("#reload").trigger("click");
}
}
if(options.beforeSendCallback && jQuery.isFunction(options.beforeSendCallback)) {
options.beforeSendCallback(this, handler, options);
}
var number = typeof index === 'number' ? 1 : files.length;
handler.adjustMaxNumberOfFiles(-number);
handler.uploadRow.find(handler.cancelSelector).click(function (e) {
handler.adjustMaxNumberOfFiles(number);
});
if (handler.autoUpload) {
handler.uploadCallBack(event, files, index, xhr, handler, callBack);
} else {
handler.uploadRow.find('.file_upload_start button').click(function (e) {
var uploadCB = function(button) {
jQuery(button).fadeOut().parent().removeClass("active");
handler.uploadCallBack(event, files, index, xhr, handler, callBack);
/* schedule another one. The reason of doing this to avoid multiple captcha check */
uploadHandler.uploadTable.find('.file_upload_start.active button').triggerHandler('click');
e.preventDefault();
};
/* validate captcha for every upload if it's enabled */
var button = this;
if(options.captcha && uploadHandler.captcha_checked == null) {
handler.validateCaptcha(files, index, xhr, handler, function() {
uploadCB(button);
});
}
else if(!options.captcha || uploadHandler.captcha_checked == true) {
uploadCB(button);
};
});
}
};
this.removeNode = function(node, callBack) {
if (node && node.length) {
var sentBefore = node.find(".file_upload_start.active").length <= 0;
node.find('.file_upload_start.active').removeClass("active");
// if node has no upload error and sentBefore (which active class has been removed from previous xhr check),
// don't remove the node(the case when server returns some errors, and we want to tell browser why it fails)
if(!node.hasClass("file_upload_error") && sentBefore) {
if (typeof callBack === "function") {
callBack();
}
}
else
node.fadeOut(function () {
node.remove();
if (typeof callBack === "function") {
try {
callBack();
} catch (e) {
node.stop();
throw e;
}
}
});
} else if (typeof callBack === "function") {
callBack();
}
};
this.deleteHandler = function (e) {
var row = jQuery(this).closest('tr');
jQuery.ajax({
url: getUrlQuery(uploadHandler.url, 'file=' + encodeURIComponent(
row.attr('data-id')
)),
type: 'DELETE',
success: function () {
uploadHandler.adjustMaxNumberOfFiles(1);
row.fadeOut(function () {
row.remove();
});
}
});
e.preventDefault();
};
this.multiButtonHandler = function (e) {
if(e.data.selector == '.file_upload_start.active') {
if(options.captcha) {
/* we need to revalidate for any click */
if(uploadHandler.captcha_checked == false) {
uploadHandler.captcha_checked = null;
}
}
uploadHandler.uploadTable.find(e.data.selector + ' button').triggerHandler('click');
}
else
uploadHandler.uploadTable.find(e.data.selector + ' button').trigger('click');
e.preventDefault();
};
this.initMultiButtons = function () {
if (uploadHandler.autoUpload) {
uploadHandler.multiButtons.find('.file_upload_start:first').hide();
} else {
uploadHandler.multiButtons.find('.file_upload_start:first')
.button()
.bind('click', {selector: '.file_upload_start.active'}, uploadHandler.multiButtonHandler);
}
uploadHandler.multiButtons.find('.file_upload_cancel:first')
.button()
.bind('click', {selector: '.file_upload_cancel'}, uploadHandler.multiButtonHandler);
};
this.destroyMultiButtons = function () {
uploadHandler.multiButtons.find(
'.file_upload_start:first, .file_upload_cancel:first'
).unbind('click', uploadHandler.multiButtonHandler).button('reset').show();
};
this.initExtended = function () {
uploadHandler.initMultiButtons();
};
this.destroyExtended = function () {
uploadHandler.destroyMultiButtons();
};
this.cancelUpload = function (event, files, index, xhr, handler) {
var readyState = xhr.readyState;
xhr.abort();
// If readyState is below 2, abort() has no effect:
if (typeof readyState !== 'number' || readyState < 2) {
handler.onAbort(event, files, index, xhr, handler);
}
/* check whether we need to disable buttons and captcha */
if(uploadHandler.uploadTable.find('.file_upload_start.active').length <= 0) {
this.completeAll();
}
};
this.validateCaptcha = function(files, index, xhr, handler, cb) {
if(options.captcha) {
jQuery(options.captcha.form).find(".error").html('');
var captcha_code = jQuery(options.captcha.form).find("#captcha_code").val();
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: options.captcha.validate,
data: {'captcha_code': captcha_code},
success: function(data) {
try {
if(data.error) {
jQuery(options.captcha.form).find(".error").html(data.error);
uploadHandler.captcha_checked = false;
return;
}
/* set to be captcha checked */
uploadHandler.captcha_checked = true;
container.find('form:first').find('input[name="captcha_code"]').val(captcha_code);
cb.apply(handler);
}
catch(e) { }
}
});
}
else
cb.apply(handler);
};
options.onComplete = function (event, files, index, xhr, handler) {
var response = handler.parseResponse(xhr, handler);
if(response.error && response.error.length > 0) {
handler.onError(response.error, files, index, xhr, handler);
}
else {
handler.completeOne(event, files, index, xhr, handler);
handler.uploadRow.addClass('file_upload_error').addClass(options.keepList ? "keeprow" : "");
if(options.onSuccess && $.isFunction(options.onSuccess)) {
options.onSuccess(this, handler, options);
}
else
handler.uploadRow.find('.file_upload_progress').append(jQuery('<div class="success"/>').append("成功上传"));
}
};
this.completeOne = function(event, files, index, xhr, handler) {
handler.uploadRow.find('.file_upload_cancel').fadeOut();
};
this.completeAll = function(list) {
if(options.captcha) {
jQuery(options.captcha.form).find(".error").html('');
jQuery(options.captcha.form).fadeOut();
jQuery(options.captcha.form).find("#captcha_code").val('');
}
uploadHandler.multiButtons.fadeOut();
};
if(!options.onCompleteAll) {
options.onCompleteAll = function(list) {
this.completeAll(list);
};
}
jQuery.extend(this, options);
};
var methods = {
init : function (options) {
return this.each(function () {
jQuery(this).fileUploadUI(new UploadHandler(jQuery(this), options));
});
},
option: function (option, value, namespace) {
if (!option || (typeof option === 'string' && typeof value === 'undefined')) {
return jQuery(this).fileUpload('option', option, value, namespace);
}
return this.each(function () {
jQuery(this).fileUploadUI('option', option, value, namespace);
});
},
destroy : function (namespace) {
return this.each(function () {
jQuery(this).fileUploadUI('destroy', namespace);
});
},
upload: function (files, namespace) {
return this.each(function () {
jQuery(this).fileUploadUI('upload', files, namespace);
});
}
};
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
jQuery.error('Method "' + method + '" does not exist on jQuery.fileUploadUIX');
}
};
相关推荐
智慧养老项目-基于JavaScript开发的老年人评估系统源码.zip智慧养老项目-基于JavaScript开发的老年人评估系统源码.zip智慧养老项目-基于JavaScript开发的老年人评估系统源码.zip智慧养老项目-基于JavaScript开发的...
【标题】"实战突击:Java项目开发案例整合源代码"是一个涵盖了多个实际应用领域的Java编程实践项目,旨在帮助开发者深入理解和应用Java技术。这个资源集合包括了FTP客户端、网络五子棋、电子商城以及BBS论坛等不同...
在“WEB前端项目开发实践”这个主题中,我们主要探讨的是如何通过理论与实践相结合的方式,掌握前端开发技术并实施实际项目。对于初学者来说,这是一个极好的学习资源,能够帮助他们逐步理解并掌握前端开发的基本...
微信小程序云开发基于JavaScript开发的电商类的小程序源码+项目说明+演示视频.tar微信小程序云开发基于JavaScript开发的电商类的小程序源码+项目说明+演示视频.tar微信小程序云开发基于JavaScript开发的电商类的小...
JS基于threejs开发的地球大屏可视化源码(动态)+项目说明.tarJS基于threejs开发的地球大屏可视化源码(动态)+项目说明.tarJS基于threejs开发的地球大屏可视化源码(动态)+项目说明.tarJS基于threejs开发的地球大屏可视...
React Native(RN)项目开发文档主要涵盖了使用React Native框架进行移动应用开发的规范、流程以及在特定版本(如0.50版本)中可能遇到的关键更新。React Native是由Facebook开发的开源库,允许开发者使用JavaScript...
在这个项目中,JavaScript被用到了上传照片、注册登录以及播放视频等功能中,这些都是JavaScript的核心应用场景。通过AJAX(异步JavaScript和XML),JavaScript还可以实现无刷新的数据交换,提供更流畅的用户体验。 ...
基于JavaScript开发的短视频去水印微信小程序源码.zip基于JavaScript开发的短视频去水印微信小程序源码.zip基于JavaScript开发的短视频去水印微信小程序源码.zip基于JavaScript开发的短视频去水印微信小程序源码.zip...
课程设计-基于JavaScript开发的微信图书推荐小程序源码+项目说明.zip课程设计-基于JavaScript开发的微信图书推荐小程序源码+项目说明.zip课程设计-基于JavaScript开发的微信图书推荐小程序源码+项目说明.zip课程设计...
基于HTML5+JavaScript开发简洁美观的网页音乐播放器源码+项目说明.tar基于HTML5+JavaScript开发简洁美观的网页音乐播放器源码+项目说明.tar基于HTML5+JavaScript开发简洁美观的网页音乐播放器源码+项目说明.tar基于...
基于javaScript+PHP开发的文件管理器+源码+项目文档+使用说明,适合毕业设计、课程设计、项目开发。项目源码已经过严格测试,可以放心参考并在此基础上延申使用~ 基于javaScript+PHP开发的文件管理器+源码+项目文档...
通过实践这些小项目,开发者不仅可以加深对jQuery的理解,还能提高动手能力,为实际项目开发打下坚实基础。在实践中,还应注意性能优化,比如使用事件代理、合理使用缓存等,以提供更好的用户体验。
基于JavaScript开发的智慧养老微信小程序源码(毕设项目).zip基于JavaScript开发的智慧养老微信小程序源码(毕设项目).zip基于JavaScript开发的智慧养老微信小程序源码(毕设项目).zip基于JavaScript开发的智慧养老微信...
基于JavaScript开发的心率检测小程序源码(课程设计).zip基于JavaScript开发的心率检测小程序源码(课程设计).zip基于JavaScript开发的心率检测小程序源码(课程设计).zip基于JavaScript开发的心率检测小程序源码(课程...
基于JavaScript开发的微信小程序识别二维码项目源码(毕设).zip基于JavaScript开发的微信小程序识别二维码项目源码(毕设).zip基于JavaScript开发的微信小程序识别二维码项目源码(毕设).zip基于JavaScript开发的微信小...
《快意编程:Ext JS Web开发技术详解》是笔者在多年项目开发过程中的经验总结,它通过丰富的实例由浅入深、循序渐进地介绍了目前采用Ext JS进行Web开发的使用方法,从而帮助软件设计人员快速掌握Ext JS开发技术的...
课设项目基于JavaScript开发的银行秒杀系统完整源码(含客户端+后台).zip课设项目基于JavaScript开发的银行秒杀系统完整源码(含客户端+后台).zip课设项目基于JavaScript开发的银行秒杀系统完整源码(含客户端+后台)....
通过这个实战项目,学习者不仅能掌握Vue2.x和Node.js的基本用法,还能了解到完整的电商项目开发流程,包括前后端交互、数据库设计、用户认证、数据安全等多个方面,对提升综合开发能力大有裨益。