jquery.multifile.js 19 KB

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