jquery.multifile.js 16 KB

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