/**
* Created by Hexu on 2018/8/23.
* 批量文件上传
*/
; ( function($) {
function init( target, opts ) {
var tar = $(target);
var height = opts.fit ? tar.parent().height() : opts.height;
var width = opts.fit ? tar.parent().width() : opts.width;
var arrFileType = getFileTypes( opts.fileType );
var maxFileSize = formattFileSize( opts.maxFileSize );
tar.data('files', [] );
tar.addClass('easyUploadsPanel');
if( opts.border ) {
--width;
--height;
tar.css('border: 1px solid drakblue');
}
else
tar.css('border', 'none');
tar.css('width', width )
.css('height', height );
var header = tar.find('.easyUploadHeader');
if( header.length > 0 ) {
header.each(function(){
$(this).find('span').off('click').remove();
$(this).remove();
});
}
header = $('');
header.css('text-align', 'center')
.css('vertical-align', 'midddle')
.css('border', 'none')
.css('margin',0)
.css('padding', 0)
.css('width', '100%')
.css('height', '32px')
.css('line-height', '32px')
.css('background-color', opts.headerBackground )
.appendTo(tar);
var filebx = header.find('input[type=file]');
if( filebx.length > 0 ) {
filebx.each(function(){
$(this).remove();
});
}
filebx = $('');
filebx.css('display', 'none').appendTo(header);
if( opts.header ) {
var txt = opts.headerText;
if( typeof(txt) == 'undefined' || txt == '' || txt == null )
txt = '点击选择图片';
$('').css('cursor', 'pointer')
.css('padding', '2px 30px')
.css('border', '1px solid orangered')
.css('border-radius', '8px')
.css('background-color', 'darkorange')
.css('height', '18px')
.css('line-height', '18px')
.html(txt).appendTo(header);
header.find('span').off('click').on('click', function(){
$(this).parent().find('input[type=file]').trigger('click');
});
}
else {
header.css('display', 'none');
}
header.find('input[type=file]').off('change').on('change', function () {
var files = this.files;
var arrFiles = [];
for (var i = 0; i < files.length; i++) {
var obj = {
file : files[i],
type: files[i].name.split('.').pop()
};
if( checkFile( obj ))
arrFiles.push( obj );
}
tar.data('files', $.merge( tar.data('files'), arrFiles ));
render(target);
});
var body = tar.find('.easyUploadBody');
if( body.length > 0 ) {
body.each(function(){
$(this).find('div.easyUploadImgInfo').off('click').remove();
$(this).off('mouseover mouseout').remove();
$(this).remove();
});
}
body = $('');
var headHeight = opts.header ? header.outerHeight(true) : 0;
body.css('border', 'none')
.css('margin', 0)
.css('padding', 0)
.css('width', '100%')
.css('overflow', 'scroll')
.css('height', height - headHeight)
.css('background-color', opts.bodyBackground)
.appendTo(tar);
tar.data('opts', opts );
function getFileTypes( types )
{
var arrTypes = [];
var arr = types.split(',');
for( var i = 0; i < arr.length; ++ i )
{
if( arr[ i ] )
arrTypes.push( arr[i].split('.').pop());
}
return arrTypes;
}
function checkFile( obj ) {
var allow = ( $.inArray('*', arrFileType ) >= 0 || $.inArray( obj.type, arrFileType ) >= 0);
allow &= ( obj.file.size <= maxFileSize );
if( allow ) {
var data = tar.data('files');
for( var i =0; i < data.length; ++i ) {
if(( obj.type === data[i].type ) &&
( obj.file.name === data[i].file.name ) &&
( obj.file.size === data[i].file.size )
){
allow = false;
break;
}
}
}
return allow;
}
function formattFileSize( size )
{
var test = /^([0-9])+(m|g|byte|b|k)$/i;
if( test.test( size )) {
switch( RegExp.$2 ) {
case 'm':
case 'M':
return RegExp.$1 * 1024 * 1024;
case 'g':
case 'G':
return RegExp.$1 * 1024 * 1024 * 1024;
default:
return RegExp.$1;
}
}
else if( /^[0-9]+$/.test( size ))
return size;
else
return 0;
}
}
function render( target )
{
var tar = $(target);
var data = tar.data('files');
var opts = tar.data('opts');
var body = tar.find('.easyUploadBody');
if( body.length <= 0 )
return;
body = $(body[0]);
body.find('div').each(function(){
$(this).find('div.easyUploadImgInfo').off('click').remove();
$(this).off('mouseover mouseout').remove();
});
for( var i = 0; i < data.length; ++i ) {
var img = $('')
.css('margin', '4px')
.css('padding', 0 )
.css('float', 'left')
.css('text-align', 'center')
.css('display', 'table-cell')
.css('vertical-align', 'midddle')
.css('border', '1px solid black')
.css('position', 'relative')
.css('z-index', 0)
.css('width', opts.imageWidth)
.css('border', '1px dotted white')
.css('height', opts.imageHeight).on({
mouseover: function () {
$(this).css('border-color', 'blue')
.find('div.easyUploadImgInfo').css('display', 'inline');
},
mouseout: function () {
$(this).css('border-color', 'white')
.find('div.easyUploadImgInfo').css('display', 'none');
}
}).addClass('easyUploadImage').appendTo(body);
var url = getFileUrl(data[i].file);
$('')
.css('position', 'absolute')
.css('top', 0)
.css('left', 0)
.css('width', '100%')
.css('height', '100%')
.css('max-height', '100%')
.css('max-width', '100%')
.attr('src', url)
.appendTo(img);
$('删除')
.css('color', 'red')
.css('font-weight', 'bold')
.css('position', 'absolute')
.css('top', 0)
.css('left', 0)
.css('margin',0)
.css('padding',0)
.css('width', '100%')
.css('height', '20px')
.css('opacity', '0.8')
.css('z-index', 10)
.css('background-color', 'rgb(240, 141, 12)')
.css('filter', 'Alpha(opacity=80)')
.css('*zoom', 1)
.css('cursor', 'pointer')
.css('display', 'none')
.on('click', function(){
var index = $(this).data('ind');
data.splice( index, 1 );
cleanFileBox( tar, true );
})
.data('ind', i )
.appendTo(img);
$('' + data[i].file.name + '')
.css('position', 'absolute')
.css('bottom', 0)
.css('margin', 0)
.css('padding', 0)
.css('width', '100%')
.css('height', '20px')
.css('color', 'white')
.css('overflow', 'hidden')
.css('white-space', 'nowrap')
.css('text-overflow', 'ellipsis')
.css('opacity', '0.6')
.css('z-index', 10)
.css('background-color', 'dimgray')
.css('filter', 'Alpha(opacity=60)')
.css('*zoom', 1)
.appendTo(img);
}
function getFileUrl( file ) {
var url = null;
var type = file.name.split('.').pop();
if( $.inArray( type, ['png', 'jpg', 'jpeg', 'bmp', 'gif' ] ) >= 0 ) {
if ( window.createObjectURL !== undefined) {
url = window.createObjectURL(file)
} else if (window.URL !== undefined) {
url = window.URL.createObjectURL(file)
} else if (window.webkitURL !== undefined) {
url = window.webkitURL.createObjectURL(file)
}
else
url = '/js/easyUpload/img/pic.png';
}
else if( $.inArray( type, ['zip', 'rar', 'jar', 'z']) >= 0 || /r[0-9]/.test( type ))
url = '/easyui/extends/extends/easyUploads/img/zip.png';
else if( $.inArray( type, ['doc', 'docx' ]) >= 0 )
url = '/easyui/extends/extends/easyUploads/img/doc.png';
else if( $.inArray( type, ['xls', 'xlsx']) >= 0 )
url = '/easyui/extends/extends/easyUploads/img/excel.png';
else if( $.inArray( type, ['pdf'] ) >= 0 )
url = '/easyui/extends/extends/easyUploads/img/pdf.png';
else
url = '/easyui/extends/extends/easyUploads/img/other.png';
return url
}
}
function cleanFileBox(target, bChanged)
{
var box = $(target).find('.easyUploadHeader input[type=file]');
box.val('');
if( bChanged )
box.trigger('change');
}
$.fn.easyUploads = function( opts, param ) {
if (typeof opts === 'string') {
var method = $.fn.easyUploads.methods[opts];
if (method) {
return method(this, param);
}
}
else {
opts = $.extend({}, $.fn.easyUploads.defaults, opts || {} );
return this.each(function () {
init( this, opts);
});
}
};
$.fn.easyUploads.methods = {
getFileCount: function(target){
return $.data(target[0], 'files' ).length;
},
selectFiles: function(target){
target.each(function(){
$(this).find('.easyUploadHeader input[type=file]').trigger('click');
});
},
doSubmit: function( target, param ){
return target.each( function(){
var opts = $(this).data('opts');
var files = $(this).data('files');
if( files.length <= 0 )
return;
var postFiles = new FormData();
for( var i = 0; i < files.length; ++i ) {
postFiles.append( 'uploads_' + i , files[i].file );
}
$.each( param.post || {}, function( k, v ){
postFiles.append( k, v )
});
$.messager.progress({title: '请稍后...', msg: '正在上传...', interval: 0});
$(document).unbind(".messager");
var bar = $.messager.progress('bar');
$.ajax({
url: param.url || opts.url,
type: 'post',
cache: false,
processData : false,
contentType : false,
data: postFiles,
xhr: function(){
var xhr = $.ajaxSettings.xhr();
if( xhr.upload ) {
xhr.upload.addEventListener("progress" , function(evt){
var loaded = evt.loaded;
var tot = evt.total;
var per = ( loaded / tot ).toFixed(2);
bar.progressbar('setValue', per );
}, false);
return xhr;
}
},
success: function(dat){
$.messager.progress('close');
var succ = param.success || opts.success;
if( typeof succ === 'function' )
succ(dat);
},
error: function(){
$.messager.progress('close');
var err = param.error || opts.error;
if( typeof err === 'function' )
err();
}
});
});
},
clear: function(target) {
return target.each(function(){
$(this).data('files', [] );
cleanFileBox( $(this), true );
});
},
destory : function(target) {
return target.each(function(){
$(this).find('.easyUploadHeader span').off('click');
$(this).data('files', [] );
cleanFileBox( $(this), true );
$(this).remove();
});
}
};
$.fn.easyUploads.defaults = {
header: true, // 是否显示标头
headerText: '', // 标头的文本
width: 680, // 宽度
height: 400, // 高度
border: false, // 是否显示边框
imageWidth: 100, // 文件缩略图大小
imageHeight: 100, // 文件缩略图大小
fit: true, // 如果为true,沾满整个父类容器,忽略高度和宽度设置
headerBackground: '#aac5e7', // 标头背景色
bodyBackground: '#1f637b', // 文件缩略区背景色
maxFileSize: '2M', // 最大上传尺寸
fileType: 'png,jpg,jpeg,bmp,gif', // 允许上传的类型
url: '', // 上传的URL
postParams: {}, // 上传时附带的参数
success: function(){}, // 上传成功时回调
error: function(){} // 上传失败时回调
};
})(jQuery);
使用方法: