/** ace file input element. custom, simple file input element to style browser's default file input. */ (function($ , undefined) { var multiplible = 'multiple' in document.createelement('input'); var hasfilelist = 'filelist' in window;//file list enabled in modern browsers var hasfilereader = 'filereader' in window; var hasfile = 'file' in window; var ace_file_input = function(element , settings) { var self = this; var attrib_values = ace.helper.getattrsettings(element, $.fn.ace_file_input.defaults); this.settings = $.extend({}, $.fn.ace_file_input.defaults, settings, attrib_values); this.$element = $(element); this.element = element; this.disabled = false; this.can_reset = true; this.$element .off('change.ace_inner_call') .on('change.ace_inner_call', function(e , ace_inner_call){ if(self.disabled) return; if(ace_inner_call === true) return;//this change event is called from above drop event and extra checkings are taken care of there return handle_on_change.call(self); //if(ret === false) e.preventdefault(); }); var parent_label = this.$element.closest('label').css({'display':'block'}) var tagname = parent_label.length == 0 ? 'label' : 'span';//if not inside a "label" tag, use "label" tag, otherwise use "span" this.$element.wrap('<'+tagname+' class="ace-file-input" />'); this.apply_settings(); this.reset_input_field();//for firefox as it keeps selected file after refresh } ace_file_input.error = { 'file_load_failed' : 1, 'image_load_failed' : 2, 'thumbnail_failed' : 3 }; ace_file_input.prototype.apply_settings = function() { var self = this; this.multi = this.$element.attr('multiple') && multiplible; this.well_style = this.settings.style == 'well'; if(this.well_style) this.$element.parent().addclass('ace-file-multiple'); else this.$element.parent().removeclass('ace-file-multiple'); this.$element.parent().find(':not(input[type=file])').remove();//remove all except our input, good for when changing settings this.$element.after(''+(this.settings.no_icon ? '' : '')+''); this.$label = this.$element.next(); this.$container = this.$element.closest('.ace-file-input'); var remove_btn = !!this.settings.icon_remove; if(remove_btn) { var btn = $('') .appendto(this.$element.parent()); btn.on(ace.click_event, function(e){ e.preventdefault(); if( !self.can_reset ) return false; var ret = true; if(self.settings.before_remove) ret = self.settings.before_remove.call(self.element); if(!ret) return false; var r = self.reset_input(); return false; }); } if(this.settings.droppable && hasfilelist) { enable_drop_functionality.call(this); } } ace_file_input.prototype.show_file_list = function($files , inner_call) { var files = typeof $files === "undefined" ? this.$element.data('ace_input_files') : $files; if(!files || files.length == 0) return; ////////////////////////////////////////////////////////////////// if(this.well_style) { this.$label.find('.ace-file-name').remove(); if(!this.settings.btn_change) this.$label.addclass('hide-placeholder'); } this.$label.attr('data-title', this.settings.btn_change).addclass('selected'); for (var i = 0; i < files.length; i++) { var filename = '', format = false; if(typeof files[i] === "string") filename = files[i]; else if(hasfile && files[i] instanceof file) filename = $.trim( files[i].name ); else if(files[i] instanceof object && files[i].hasownproperty('name')) { //format & name specified by user (pre-displaying name, etc) filename = files[i].name; if(files[i].hasownproperty('type')) format = files[i].type; if(!files[i].hasownproperty('path')) files[i].path = files[i].name; } else continue; var index = filename.lastindexof("\\") + 1; if(index == 0)index = filename.lastindexof("/") + 1; filename = filename.substr(index); if(format == false) { if((/\.(jpe?g|png|gif|svg|bmp|tiff?)$/i).test(filename)) { format = 'image'; } else if((/\.(mpe?g|flv|mov|avi|swf|mp4|mkv|webm|wmv|3gp)$/i).test(filename)) { format = 'video'; } else if((/\.(mp3|ogg|wav|wma|amr|aac)$/i).test(filename)) { format = 'audio'; } else format = 'file'; } var fileicons = { 'file' : 'fa fa-file', 'image' : 'fa fa-picture-o file-image', 'video' : 'fa fa-film file-video', 'audio' : 'fa fa-music file-audio' }; var fileicon = fileicons[format]; if(!this.well_style) this.$label.find('.ace-file-name').attr({'data-title':filename}).find(ace.vars['.icon']).attr('class', ace.vars['icon'] + fileicon); else { this.$label.append(''); var type = (inner_call === true && hasfile && files[i] instanceof file) ? $.trim(files[i].type) : ''; var can_preview = hasfilereader && this.settings.thumbnail && ( (type.length > 0 && type.match('image')) || (type.length == 0 && format == 'image') )//the second one is for older android's default browser which gives an empty text for file.type if(can_preview) { var self = this; $.when(preview_image.call(this, files[i])).fail(function(result){ //called on failure to load preview if(self.settings.preview_error) self.settings.preview_error.call(self, filename, result.code); }) } } } return true; } ace_file_input.prototype.reset_input = function() { this.reset_input_ui(); this.reset_input_field(); } ace_file_input.prototype.reset_input_ui = function() { this.$label.attr({'data-title':this.settings.btn_choose, 'class':'ace-file-container'}) .find('.ace-file-name:first').attr({'data-title':this.settings.no_file , 'class':'ace-file-name'}) .find(ace.vars['.icon']).attr('class', ace.vars['icon'] + this.settings.no_icon) .prev('img').remove(); if(!this.settings.no_icon) this.$label.find(ace.vars['.icon']).remove(); this.$label.find('.ace-file-name').not(':first').remove(); this.reset_input_data(); //if(ace.vars['old_ie']) ace.helper.redraw(this.$container[0]); } ace_file_input.prototype.reset_input_field = function() { //http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery/13351234#13351234 this.$element.wrap('
').parent().get(0).reset(); this.$element.unwrap(); //strangely when reset is called on this temporary inner form //only **ie9/10** trigger 'reset' on the outer form as well //and as we have mentioned to reset input on outer form reset //it causes infinite recusrsion by coming back to reset_input_field //thus calling reset again and again and again //so because when "reset" button of outer form is hit, file input is automatically reset //we just reset_input_ui to avoid recursion } ace_file_input.prototype.reset_input_data = function() { if(this.$element.data('ace_input_files')) { this.$element.removedata('ace_input_files'); this.$element.removedata('ace_input_method'); } } ace_file_input.prototype.enable_reset = function(can_reset) { this.can_reset = can_reset; } ace_file_input.prototype.disable = function() { this.disabled = true; this.$element.attr('disabled', 'disabled').addclass('disabled'); } ace_file_input.prototype.enable = function() { this.disabled = false; this.$element.removeattr('disabled').removeclass('disabled'); } ace_file_input.prototype.files = function() { return $(this).data('ace_input_files') || null; } ace_file_input.prototype.method = function() { return $(this).data('ace_input_method') || ''; } ace_file_input.prototype.update_settings = function(new_settings) { this.settings = $.extend({}, this.settings, new_settings); this.apply_settings(); } ace_file_input.prototype.loading = function(is_loading) { if(is_loading === false) { this.$container.find('.ace-file-overlay').remove(); this.element.removeattribute('readonly'); } else { var inside = typeof is_loading === 'string' ? is_loading : ''; var loader = this.$container.find('.ace-file-overlay'); if(loader.length == 0) { loader = $('
').appendto(this.$container); loader.on('click tap', function(e) { e.stopimmediatepropagation(); e.preventdefault(); return false; }); this.element.setattribute('readonly' , 'true');//for ie } loader.empty().append(inside); } } var enable_drop_functionality = function() { var self = this; var dropbox = this.$element.parent(); dropbox .off('dragenter') .on('dragenter', function(e){ e.preventdefault(); e.stoppropagation(); }) .off('dragover') .on('dragover', function(e){ e.preventdefault(); e.stoppropagation(); }) .off('drop') .on('drop', function(e){ e.preventdefault(); e.stoppropagation(); if(self.disabled) return; var dt = e.originalevent.datatransfer; var file_list = dt.files; if(!self.multi && file_list.length > 1) {//single file upload, but dragged multiple files var tmpfiles = []; tmpfiles.push(file_list[0]); file_list = tmpfiles;//keep only first file } file_list = processfiles.call(self, file_list, true);//true means files have been selected, not dropped if(file_list === false) return false; self.$element.data('ace_input_method', 'drop'); self.$element.data('ace_input_files', file_list);//save files data to be used later by user self.show_file_list(file_list , true); self.$element.triggerhandler('change' , [true]);//true means ace_inner_call return true; }); } var handle_on_change = function() { var file_list = this.element.files || [this.element.value];/** make it an array */ file_list = processfiles.call(this, file_list, false);//false means files have been selected, not dropped if(file_list === false) return false; this.$element.data('ace_input_method', 'select'); this.$element.data('ace_input_files', file_list); this.show_file_list(file_list , true); return true; } var preview_image = function(file) { var self = this; var $span = self.$label.find('.ace-file-name:last');//it should be out of onload, otherwise all onloads may target the same span because of delays var deferred = new $.deferred; var getimage = function(src) { $span.prepend(""); var img = $span.find('img:last').get(0); $(img).one('load', function() { imgloaded.call(null, img); }).one('error', function() { imgfailed.call(null, img); }); img.src = src; } var imgloaded = function(img) { //if image loaded successfully var size = 50; if(self.settings.thumbnail == 'large') size = 150; else if(self.settings.thumbnail == 'fit') size = $span.width(); $span.addclass(size > 50 ? 'large' : ''); var thumb = get_thumbnail(img, size/**, file.type*/); if(thumb == null) { //if making thumbnail fails $(this).remove(); deferred.reject({code:ace_file_input.error['thumbnail_failed']}); return; } var w = thumb.w, h = thumb.h; if(self.settings.thumbnail == 'small') {w=h=size;}; $(img).css({'background-image':'url('+thumb.src+')' , width:w, height:h}) .data('thumb', thumb.src) .attr({src:'data:image/png;base64,ivborw0kggoaaaansuheugaaaaeaaaabcayaaaaffcsjaaaaduleqvqimwngygbgaaaabqabh6fo1aaaaabjru5erkjggg=='}) .show() /////////////////// deferred.resolve(); } var imgfailed = function(img) { //for example when a file has image extenstion, but format is something else $span.find('img').remove(); deferred.reject({code:ace_file_input.error['image_load_failed']}); } if(hasfile && file instanceof file) { var reader = new filereader(); reader.onload = function (e) { getimage(e.target.result); } reader.onerror = function (e) { deferred.reject({code:ace_file_input.error['file_load_failed']}); } reader.readasdataurl(file); } else { if(file instanceof object && file.hasownproperty('path')) { getimage(file.path);//file is a file name (path) --- this is used to pre-show user-selected image } } return deferred.promise(); } var get_thumbnail = function(img, size, type) { var w = img.width, h = img.height; //**ie10** is not giving correct width using img.width so we use $(img).width() w = w > 0 ? w : $(img).width() h = h > 0 ? h : $(img).height() if(w > size || h > size) { if(w > h) { h = parseint(size/w * h); w = size; } else { w = parseint(size/h * w); h = size; } } var dataurl try { var canvas = document.createelement('canvas'); canvas.width = w; canvas.height = h; var context = canvas.getcontext('2d'); context.drawimage(img, 0, 0, img.width, img.height, 0, 0, w, h); dataurl = canvas.todataurl(/*type == 'image/jpeg' ? type : 'image/png', 10*/) } catch(e) { dataurl = null; } if(! dataurl) return null; //there was only one image that failed in firefox completely randomly! so let's double check things if( !( /^data\:image\/(png|jpe?g|gif);base64,[0-9a-za-z\+\/\=]+$/.test(dataurl)) ) dataurl = null; if(! dataurl) return null; return {src: dataurl, w:w, h:h}; } var processfiles = function(file_list, dropped) { var ret = checkfilelist.call(this, file_list, dropped); if(ret === -1) { this.reset_input(); return false; } if( !ret || ret.length == 0 ) { if( !this.$element.data('ace_input_files') ) this.reset_input(); //if nothing selected before, reset because of the newly unacceptable (ret=false||length=0) selection //otherwise leave the previous selection intact?!!! return false; } if (ret instanceof array || (hasfilelist && ret instanceof filelist)) file_list = ret; ret = true; if(this.settings.before_change) ret = this.settings.before_change.call(this.element, file_list, dropped); if(ret === -1) { this.reset_input(); return false; } if(!ret || ret.length == 0) { if( !this.$element.data('ace_input_files') ) this.reset_input(); return false; } //inside before_change you can return a modified file array as result if (ret instanceof array || (hasfilelist && ret instanceof filelist)) file_list = ret; return file_list; } var getextregex = function(ext) { if(!ext) return null; if(typeof ext === 'string') ext = [ext]; if(ext.length == 0) return null; return new regexp("\.(?:"+ext.join('|')+")$", "i"); } var getmimeregex = function(mime) { if(!mime) return null; if(typeof mime === 'string') mime = [mime]; if(mime.length == 0) return null; return new regexp("^(?:"+mime.join('|').replace(/\//g, "\\/")+")$", "i"); } var checkfilelist = function(files, dropped) { var allowext = getextregex(this.settings.allowext); var denyext = getextregex(this.settings.denyext); var allowmime = getmimeregex(this.settings.allowmime); var denymime = getmimeregex(this.settings.denymime); var maxsize = this.settings.maxsize || false; if( !(allowext || denyext || allowmime || denymime || maxsize) ) return true;//no checking required var safe_files = []; var error_list = {} for(var f = 0; f < files.length; f++) { var file = files[f]; //file is either a string(file name) or a file object var filename = !hasfile ? file : file.name; if( allowext && !allowext.test(filename) ) { //extension not matching whitelist, so drop it if(!('ext' in error_list)) error_list['ext'] = []; error_list['ext'].push(filename); continue; } else if( denyext && denyext.test(filename) ) { //extension is matching blacklist, so drop it if(!('ext' in error_list)) error_list['ext'] = []; error_list['ext'].push(filename); continue; } var type; if( !hasfile ) { //in browsers that don't support filereader api safe_files.push(file); continue; } else if((type = $.trim(file.type)).length > 0) { //there is a mimetype for file so let's check against are rules if( allowmime && !allowmime.test(type) ) { //mimetype is not matching whitelist, so drop it if(!('mime' in error_list)) error_list['mime'] = []; error_list['mime'].push(filename); continue; } else if( denymime && denymime.test(type) ) { //mimetype is matching blacklist, so drop it if(!('mime' in error_list)) error_list['mime'] = []; error_list['mime'].push(filename); continue; } } if( maxsize && file.size > maxsize ) { //file size is not acceptable if(!('size' in error_list)) error_list['size'] = []; error_list['size'].push(filename); continue; } safe_files.push(file) } if(safe_files.length == files.length) return files;//return original file list if all are valid ///////// var error_count = {'ext': 0, 'mime': 0, 'size': 0} if( 'ext' in error_list ) error_count['ext'] = error_list['ext'].length; if( 'mime' in error_list ) error_count['mime'] = error_list['mime'].length; if( 'size' in error_list ) error_count['size'] = error_list['size'].length; var event this.$element.trigger( event = new $.event('file.error.ace'), { 'file_count': files.length, 'invalid_count' : files.length - safe_files.length, 'error_list' : error_list, 'error_count' : error_count, 'dropped': dropped } ); if ( event.isdefaultprevented() ) return -1;//it will reset input ////////// return safe_files;//return safe_files } /////////////////////////////////////////// $.fn.acefileinput = $.fn.ace_file_input = function (option,value) { var retval; var $set = this.each(function () { var $this = $(this); var data = $this.data('ace_file_input'); var options = typeof option === 'object' && option; if (!data) $this.data('ace_file_input', (data = new ace_file_input(this, options))); if (typeof option === 'string') retval = data[option](value); }); return (retval === undefined) ? $set : retval; }; $.fn.ace_file_input.defaults = { style: false, no_file: 'no file ...', no_icon: 'fa fa-upload', btn_choose: 'choose', btn_change: 'change', icon_remove: 'fa fa-times', droppable: false, thumbnail: false,//large, fit, small allowext: null, denyext: null, allowmime: null, denymime: null, maxsize: false, //callbacks before_change: null, before_remove: null, preview_error: null } })(window.jquery);