/demo/yii/web/js/source/jquery.multifile.js

https://bitbucket.org/sakhalin/yii-bootstrap · JavaScript · 536 lines · 218 code · 96 blank · 222 comment · 58 complexity · 778f6254c4210c2479548d9c1ee5339f MD5 · raw file

  1. /*
  2. ### jQuery Multiple File Upload Plugin v1.47 - 2010-03-26 ###
  3. * Home: http://www.fyneworks.com/jquery/multiple-file-upload/
  4. * Code: http://code.google.com/p/jquery-multifile-plugin/
  5. *
  6. * Dual licensed under the MIT and GPL licenses:
  7. * http://www.opensource.org/licenses/mit-license.php
  8. * http://www.gnu.org/licenses/gpl.html
  9. ###
  10. */
  11. /*# AVOID COLLISIONS #*/
  12. ;if(window.jQuery) (function($){
  13. /*# AVOID COLLISIONS #*/
  14. // plugin initialization
  15. $.fn.MultiFile = function(options){
  16. if(this.length==0) return this; // quick fail
  17. // Handle API methods
  18. if(typeof arguments[0]=='string'){
  19. // Perform API methods on individual elements
  20. if(this.length>1){
  21. var args = arguments;
  22. return this.each(function(){
  23. $.fn.MultiFile.apply($(this), args);
  24. });
  25. };
  26. // Invoke API method handler
  27. $.fn.MultiFile[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
  28. // Quick exit...
  29. return this;
  30. };
  31. // Initialize options for this call
  32. var options = $.extend(
  33. {}/* new object */,
  34. $.fn.MultiFile.options/* default options */,
  35. options || {} /* just-in-time options */
  36. );
  37. // Empty Element Fix!!!
  38. // this code will automatically intercept native form submissions
  39. // and disable empty file elements
  40. $('form')
  41. .not('MultiFile-intercepted')
  42. .addClass('MultiFile-intercepted')
  43. .submit($.fn.MultiFile.disableEmpty);
  44. //### http://plugins.jquery.com/node/1363
  45. // utility method to integrate this plugin with others...
  46. if($.fn.MultiFile.options.autoIntercept){
  47. $.fn.MultiFile.intercept( $.fn.MultiFile.options.autoIntercept /* array of methods to intercept */ );
  48. $.fn.MultiFile.options.autoIntercept = null; /* only run this once */
  49. };
  50. // loop through each matched element
  51. this
  52. .not('.MultiFile-applied')
  53. .addClass('MultiFile-applied')
  54. .each(function(){
  55. //#####################################################################
  56. // MAIN PLUGIN FUNCTIONALITY - START
  57. //#####################################################################
  58. // BUG 1251 FIX: http://plugins.jquery.com/project/comments/add/1251
  59. // variable group_count would repeat itself on multiple calls to the plugin.
  60. // this would cause a conflict with multiple elements
  61. // changes scope of variable to global so id will be unique over n calls
  62. window.MultiFile = (window.MultiFile || 0) + 1;
  63. var group_count = window.MultiFile;
  64. // Copy parent attributes - Thanks to Jonas Wagner
  65. // we will use this one to create new input elements
  66. var MultiFile = {e:this, E:$(this), clone:$(this).clone()};
  67. //===
  68. //# USE CONFIGURATION
  69. if(typeof options=='number') options = {max:options};
  70. var o = $.extend({},
  71. $.fn.MultiFile.options,
  72. options || {},
  73. ($.metadata? MultiFile.E.metadata(): ($.meta?MultiFile.E.data():null)) || {}, /* metadata options */
  74. {} /* internals */
  75. );
  76. // limit number of files that can be selected?
  77. if(!(o.max>0) /*IsNull(MultiFile.max)*/){
  78. o.max = MultiFile.E.attr('maxlength');
  79. if(!(o.max>0) /*IsNull(MultiFile.max)*/){
  80. o.max = (String(MultiFile.e.className.match(/\b(max|limit)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];
  81. if(!(o.max>0)) o.max = -1;
  82. else o.max = String(o.max).match(/[0-9]+/gi)[0];
  83. }
  84. };
  85. o.max = new Number(o.max);
  86. // limit extensions?
  87. o.accept = o.accept || MultiFile.E.attr('accept') || '';
  88. if(!o.accept){
  89. o.accept = (MultiFile.e.className.match(/\b(accept\-[\w\|]+)\b/gi)) || '';
  90. o.accept = new String(o.accept).replace(/^(accept|ext)\-/i,'');
  91. };
  92. //===
  93. // APPLY CONFIGURATION
  94. $.extend(MultiFile, o || {});
  95. MultiFile.STRING = $.extend({},$.fn.MultiFile.options.STRING,MultiFile.STRING);
  96. //===
  97. //#########################################
  98. // PRIVATE PROPERTIES/METHODS
  99. $.extend(MultiFile, {
  100. n: 0, // How many elements are currently selected?
  101. slaves: [], files: [],
  102. instanceKey: MultiFile.e.id || 'MultiFile'+String(group_count), // Instance Key?
  103. generateID: function(z){ return MultiFile.instanceKey + (z>0 ?'_F'+String(z):''); },
  104. trigger: function(event, element){
  105. var handler = MultiFile[event], value = $(element).attr('value');
  106. if(handler){
  107. var returnValue = handler(element, value, MultiFile);
  108. if( returnValue!=null ) return returnValue;
  109. }
  110. return true;
  111. }
  112. });
  113. //===
  114. // Setup dynamic regular expression for extension validation
  115. // - thanks to John-Paul Bader: http://smyck.de/2006/08/11/javascript-dynamic-regular-expresions/
  116. if(String(MultiFile.accept).length>1){
  117. MultiFile.accept = MultiFile.accept.replace(/\W+/g,'|').replace(/^\W|\W$/g,'');
  118. MultiFile.rxAccept = new RegExp('\\.('+(MultiFile.accept?MultiFile.accept:'')+')$','gi');
  119. };
  120. //===
  121. // Create wrapper to hold our file list
  122. MultiFile.wrapID = MultiFile.instanceKey+'_wrap'; // Wrapper ID?
  123. MultiFile.E.wrap('<div class="MultiFile-wrap" id="'+MultiFile.wrapID+'"></div>');
  124. MultiFile.wrapper = $('#'+MultiFile.wrapID+'');
  125. //===
  126. // MultiFile MUST have a name - default: file1[], file2[], file3[]
  127. MultiFile.e.name = MultiFile.e.name || 'file'+ group_count +'[]';
  128. //===
  129. if(!MultiFile.list){
  130. // Create a wrapper for the list
  131. // * OPERA BUG: NO_MODIFICATION_ALLOWED_ERR ('list' is a read-only property)
  132. // this change allows us to keep the files in the order they were selected
  133. MultiFile.wrapper.append( '<div class="MultiFile-list" id="'+MultiFile.wrapID+'_list"></div>' );
  134. MultiFile.list = $('#'+MultiFile.wrapID+'_list');
  135. };
  136. MultiFile.list = $(MultiFile.list);
  137. //===
  138. // Bind a new element
  139. MultiFile.addSlave = function( slave, slave_count ){
  140. //if(window.console) console.log('MultiFile.addSlave',slave_count);
  141. // Keep track of how many elements have been displayed
  142. MultiFile.n++;
  143. // Add reference to master element
  144. slave.MultiFile = MultiFile;
  145. // BUG FIX: http://plugins.jquery.com/node/1495
  146. // Clear identifying properties from clones
  147. if(slave_count>0) slave.id = slave.name = '';
  148. // Define element's ID and name (upload components need this!)
  149. //slave.id = slave.id || MultiFile.generateID(slave_count);
  150. if(slave_count>0) slave.id = MultiFile.generateID(slave_count);
  151. //FIX for: http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=23
  152. // 2008-Apr-29: New customizable naming convention (see url below)
  153. // http://groups.google.com/group/jquery-dev/browse_frm/thread/765c73e41b34f924#
  154. slave.name = String(MultiFile.namePattern
  155. /*master name*/.replace(/\$name/gi,$(MultiFile.clone).attr('name'))
  156. /*master id */.replace(/\$id/gi, $(MultiFile.clone).attr('id'))
  157. /*group count*/.replace(/\$g/gi, group_count)//(group_count>0?group_count:''))
  158. /*slave count*/.replace(/\$i/gi, slave_count)//(slave_count>0?slave_count:''))
  159. );
  160. // If we've reached maximum number, disable input slave
  161. if( (MultiFile.max > 0) && ((MultiFile.n-1) > (MultiFile.max)) )//{ // MultiFile.n Starts at 1, so subtract 1 to find true count
  162. slave.disabled = true;
  163. //};
  164. // Remember most recent slave
  165. MultiFile.current = MultiFile.slaves[slave_count] = slave;
  166. // We'll use jQuery from now on
  167. slave = $(slave);
  168. // Clear value
  169. slave.val('').attr('value','')[0].value = '';
  170. // Stop plugin initializing on slaves
  171. slave.addClass('MultiFile-applied');
  172. // Triggered when a file is selected
  173. slave.change(function(){
  174. //if(window.console) console.log('MultiFile.slave.change',slave_count);
  175. // Lose focus to stop IE7 firing onchange again
  176. $(this).blur();
  177. //# Trigger Event! onFileSelect
  178. if(!MultiFile.trigger('onFileSelect', this, MultiFile)) return false;
  179. //# End Event!
  180. //# Retrive value of selected file from element
  181. var ERROR = '', v = String(this.value || ''/*.attr('value)*/);
  182. // check extension
  183. if(MultiFile.accept && v && !v.match(MultiFile.rxAccept))//{
  184. ERROR = MultiFile.STRING.denied.replace('$ext', String(v.match(/\.\w{1,4}$/gi)));
  185. //}
  186. //};
  187. // Disallow duplicates
  188. for(var f in MultiFile.slaves)//{
  189. if(MultiFile.slaves[f] && MultiFile.slaves[f]!=this)//{
  190. //console.log(MultiFile.slaves[f],MultiFile.slaves[f].value);
  191. if(MultiFile.slaves[f].value==v)//{
  192. ERROR = MultiFile.STRING.duplicate.replace('$file', v.match(/[^\/\\]+$/gi));
  193. //};
  194. //};
  195. //};
  196. // Create a new file input element
  197. var newEle = $(MultiFile.clone).clone();// Copy parent attributes - Thanks to Jonas Wagner
  198. //# Let's remember which input we've generated so
  199. // we can disable the empty ones before submission
  200. // See: http://plugins.jquery.com/node/1495
  201. newEle.addClass('MultiFile');
  202. // Handle error
  203. if(ERROR!=''){
  204. // Handle error
  205. MultiFile.error(ERROR);
  206. // 2007-06-24: BUG FIX - Thanks to Adrian Wróbel <adrian [dot] wrobel [at] gmail.com>
  207. // Ditch the trouble maker and add a fresh new element
  208. MultiFile.n--;
  209. MultiFile.addSlave(newEle[0], slave_count);
  210. slave.parent().prepend(newEle);
  211. slave.remove();
  212. return false;
  213. };
  214. // Hide this element (NB: display:none is evil!)
  215. $(this).css({ position:'absolute', top: '-3000px' });
  216. // Add new element to the form
  217. slave.after(newEle);
  218. // Update list
  219. MultiFile.addToList( this, slave_count );
  220. // Bind functionality
  221. MultiFile.addSlave( newEle[0], slave_count+1 );
  222. //# Trigger Event! afterFileSelect
  223. if(!MultiFile.trigger('afterFileSelect', this, MultiFile)) return false;
  224. //# End Event!
  225. }); // slave.change()
  226. // Save control to element
  227. $(slave).data('MultiFile', MultiFile);
  228. };// MultiFile.addSlave
  229. // Bind a new element
  230. // Add a new file to the list
  231. MultiFile.addToList = function( slave, slave_count ){
  232. //if(window.console) console.log('MultiFile.addToList',slave_count);
  233. //# Trigger Event! onFileAppend
  234. if(!MultiFile.trigger('onFileAppend', slave, MultiFile)) return false;
  235. //# End Event!
  236. // Create label elements
  237. var
  238. r = $('<div class="MultiFile-label"></div>'),
  239. v = String(slave.value || ''/*.attr('value)*/),
  240. a = $('<span class="MultiFile-title" title="'+MultiFile.STRING.selected.replace('$file', v)+'">'+MultiFile.STRING.file.replace('$file', v.match(/[^\/\\]+$/gi)[0])+'</span>'),
  241. b = $('<a class="MultiFile-remove" href="#'+MultiFile.wrapID+'">'+MultiFile.STRING.remove+'</a>');
  242. // Insert label
  243. MultiFile.list.append(
  244. r.append(b, ' ', a)
  245. );
  246. b
  247. .click(function(){
  248. //# Trigger Event! onFileRemove
  249. if(!MultiFile.trigger('onFileRemove', slave, MultiFile)) return false;
  250. //# End Event!
  251. MultiFile.n--;
  252. MultiFile.current.disabled = false;
  253. // Remove element, remove label, point to current
  254. MultiFile.slaves[slave_count] = null;
  255. $(slave).remove();
  256. $(this).parent().remove();
  257. // Show most current element again (move into view) and clear selection
  258. $(MultiFile.current).css({ position:'', top: '' });
  259. $(MultiFile.current).reset().val('').attr('value', '')[0].value = '';
  260. //# Trigger Event! afterFileRemove
  261. if(!MultiFile.trigger('afterFileRemove', slave, MultiFile)) return false;
  262. //# End Event!
  263. return false;
  264. });
  265. //# Trigger Event! afterFileAppend
  266. if(!MultiFile.trigger('afterFileAppend', slave, MultiFile)) return false;
  267. //# End Event!
  268. }; // MultiFile.addToList
  269. // Add element to selected files list
  270. // Bind functionality to the first element
  271. if(!MultiFile.MultiFile) MultiFile.addSlave(MultiFile.e, 0);
  272. // Increment control count
  273. //MultiFile.I++; // using window.MultiFile
  274. MultiFile.n++;
  275. // Save control to element
  276. MultiFile.E.data('MultiFile', MultiFile);
  277. //#####################################################################
  278. // MAIN PLUGIN FUNCTIONALITY - END
  279. //#####################################################################
  280. }); // each element
  281. };
  282. /*--------------------------------------------------------*/
  283. /*
  284. ### Core functionality and API ###
  285. */
  286. $.extend($.fn.MultiFile, {
  287. /**
  288. * This method removes all selected files
  289. *
  290. * Returns a jQuery collection of all affected elements.
  291. *
  292. * @name reset
  293. * @type jQuery
  294. * @cat Plugins/MultiFile
  295. * @author Diego A. (http://www.fyneworks.com/)
  296. *
  297. * @example $.fn.MultiFile.reset();
  298. */
  299. reset: function(){
  300. var settings = $(this).data('MultiFile');
  301. //if(settings) settings.wrapper.find('a.MultiFile-remove').click();
  302. if(settings) settings.list.find('a.MultiFile-remove').click();
  303. return $(this);
  304. },
  305. /**
  306. * This utility makes it easy to disable all 'empty' file elements in the document before submitting a form.
  307. * It marks the affected elements so they can be easily re-enabled after the form submission or validation.
  308. *
  309. * Returns a jQuery collection of all affected elements.
  310. *
  311. * @name disableEmpty
  312. * @type jQuery
  313. * @cat Plugins/MultiFile
  314. * @author Diego A. (http://www.fyneworks.com/)
  315. *
  316. * @example $.fn.MultiFile.disableEmpty();
  317. * @param String class (optional) A string specifying a class to be applied to all affected elements - Default: 'mfD'.
  318. */
  319. disableEmpty: function(klass){ klass = (typeof(klass)=='string'?klass:'')||'mfD';
  320. var o = [];
  321. $('input:file.MultiFile').each(function(){ if($(this).val()=='') o[o.length] = this; });
  322. return $(o).each(function(){ this.disabled = true }).addClass(klass);
  323. },
  324. /**
  325. * This method re-enables 'empty' file elements that were disabled (and marked) with the $.fn.MultiFile.disableEmpty method.
  326. *
  327. * Returns a jQuery collection of all affected elements.
  328. *
  329. * @name reEnableEmpty
  330. * @type jQuery
  331. * @cat Plugins/MultiFile
  332. * @author Diego A. (http://www.fyneworks.com/)
  333. *
  334. * @example $.fn.MultiFile.reEnableEmpty();
  335. * @param String klass (optional) A string specifying the class that was used to mark affected elements - Default: 'mfD'.
  336. */
  337. reEnableEmpty: function(klass){ klass = (typeof(klass)=='string'?klass:'')||'mfD';
  338. return $('input:file.'+klass).removeClass(klass).each(function(){ this.disabled = false });
  339. },
  340. /**
  341. * This method will intercept other jQuery plugins and disable empty file input elements prior to form submission
  342. *
  343. * @name intercept
  344. * @cat Plugins/MultiFile
  345. * @author Diego A. (http://www.fyneworks.com/)
  346. *
  347. * @example $.fn.MultiFile.intercept();
  348. * @param Array methods (optional) Array of method names to be intercepted
  349. */
  350. intercepted: {},
  351. intercept: function(methods, context, args){
  352. var method, value; args = args || [];
  353. if(args.constructor.toString().indexOf("Array")<0) args = [ args ];
  354. if(typeof(methods)=='function'){
  355. $.fn.MultiFile.disableEmpty();
  356. value = methods.apply(context || window, args);
  357. //SEE-http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27
  358. setTimeout(function(){ $.fn.MultiFile.reEnableEmpty() },1000);
  359. return value;
  360. };
  361. if(methods.constructor.toString().indexOf("Array")<0) methods = [methods];
  362. for(var i=0;i<methods.length;i++){
  363. method = methods[i]+''; // make sure that we have a STRING
  364. if(method) (function(method){ // make sure that method is ISOLATED for the interception
  365. $.fn.MultiFile.intercepted[method] = $.fn[method] || function(){};
  366. $.fn[method] = function(){
  367. $.fn.MultiFile.disableEmpty();
  368. value = $.fn.MultiFile.intercepted[method].apply(this, arguments);
  369. //SEE-http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27
  370. setTimeout(function(){ $.fn.MultiFile.reEnableEmpty() },1000);
  371. return value;
  372. }; // interception
  373. })(method); // MAKE SURE THAT method IS ISOLATED for the interception
  374. };// for each method
  375. } // $.fn.MultiFile.intercept
  376. });
  377. /*--------------------------------------------------------*/
  378. /*
  379. ### Default Settings ###
  380. eg.: You can override default control like this:
  381. $.fn.MultiFile.options.accept = 'gif|jpg';
  382. */
  383. $.fn.MultiFile.options = { //$.extend($.fn.MultiFile, { options: {
  384. accept: '', // accepted file extensions
  385. max: -1, // maximum number of selectable files
  386. // name to use for newly created elements
  387. namePattern: '$name', // same name by default (which creates an array)
  388. // STRING: collection lets you show messages in different languages
  389. STRING: {
  390. remove:'x',
  391. denied:'You cannot select a $ext file.\nTry again...',
  392. file:'$file',
  393. selected:'File selected: $file',
  394. duplicate:'This file has already been selected:\n$file'
  395. },
  396. // name of methods that should be automcatically intercepted so the plugin can disable
  397. // extra file elements that are empty before execution and automatically re-enable them afterwards
  398. autoIntercept: [ 'submit', 'ajaxSubmit', 'ajaxForm', 'validate', 'valid' /* array of methods to intercept */ ],
  399. // error handling function
  400. error: function(s){
  401. /*
  402. ERROR! blockUI is not currently working in IE
  403. if($.blockUI){
  404. $.blockUI({
  405. message: s.replace(/\n/gi,'<br/>'),
  406. css: {
  407. border:'none', padding:'15px', size:'12.0pt',
  408. backgroundColor:'#900', color:'#fff',
  409. opacity:'.8','-webkit-border-radius': '10px','-moz-border-radius': '10px'
  410. }
  411. });
  412. window.setTimeout($.unblockUI, 2000);
  413. }
  414. else//{// save a byte!
  415. */
  416. alert(s);
  417. //}// save a byte!
  418. }
  419. }; //} });
  420. /*--------------------------------------------------------*/
  421. /*
  422. ### Additional Methods ###
  423. Required functionality outside the plugin's scope
  424. */
  425. // Native input reset method - because this alone doesn't always work: $(element).val('').attr('value', '')[0].value = '';
  426. $.fn.reset = function(){ return this.each(function(){ try{ this.reset(); }catch(e){} }); };
  427. /*--------------------------------------------------------*/
  428. /*
  429. ### Default implementation ###
  430. The plugin will attach itself to file inputs
  431. with the class 'multi' when the page loads
  432. */
  433. $(function(){
  434. //$("input:file.multi").MultiFile();
  435. $("input[type=file].multi").MultiFile();
  436. });
  437. /*# AVOID COLLISIONS #*/
  438. })(jQuery);
  439. /*# AVOID COLLISIONS #*/