Anonymous 3D Imageboard http://cyberia.digital/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

914 lines
30KB

  1. /*
  2. ### jQuery Multiple File Selection Plugin v2.2.2 - 2016-06-16 ###
  3. * Home: http://www.fyneworks.com/jquery/multifile/
  4. * Code: https://github.com/fyneworks/multifile
  5. *
  6. * Licensed under http://en.wikipedia.org/wiki/MIT_License
  7. */
  8. /*# AVOID COLLISIONS #*/
  9. ;
  10. if (window.jQuery)(function ($) {
  11. "use strict";
  12. /*# AVOID COLLISIONS #*/
  13. // size label function (shows kb and mb where accordingly)
  14. function sl(x) {
  15. return x > 1048576 ? (x / 1048576).toFixed(1) + 'Mb' : (x==1024?'1Mb': (x / 1024).toFixed(1) + 'Kb' )
  16. };
  17. // utility function to return an array of
  18. function FILE_LIST(x){
  19. return ((x.files&&x.files.length) ? x.files : null) || [{
  20. name: x.value,
  21. size: 0,
  22. type: ((x.value || '').match(/[^\.]+$/i) || [''])[0]
  23. }];
  24. };
  25. // plugin initialization
  26. $.fn.MultiFile = function (options) {
  27. if (this.length == 0) return this; // quick fail
  28. // Handle API methods
  29. if (typeof arguments[0] == 'string') {
  30. // Perform API methods on individual elements
  31. if (this.length > 1) {
  32. var args = arguments;
  33. return this.each(function () {
  34. $.fn.MultiFile.apply($(this), args);
  35. });
  36. };
  37. // Invoke API method handler (and return whatever it wants to return)
  38. return $.fn.MultiFile[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
  39. };
  40. // Accept number
  41. if (typeof options == 'number') {
  42. options = {max: options};
  43. };
  44. // Initialize options for this call
  45. var options = $.extend({} /* new object */ ,
  46. $.fn.MultiFile.options /* default options */ ,
  47. options || {} /* just-in-time options */
  48. );
  49. // Empty Element Fix!!!
  50. // this code will automatically intercept native form submissions
  51. // and disable empty file elements
  52. $('form')
  53. .not('MultiFile-intercepted')
  54. .addClass('MultiFile-intercepted')
  55. .submit($.fn.MultiFile.disableEmpty);
  56. //### http://plugins.jquery.com/node/1363
  57. // utility method to integrate this plugin with others...
  58. if ($.fn.MultiFile.options.autoIntercept) {
  59. $.fn.MultiFile.intercept($.fn.MultiFile.options.autoIntercept /* array of methods to intercept */ );
  60. $.fn.MultiFile.options.autoIntercept = null; /* only run this once */
  61. };
  62. // loop through each matched element
  63. this
  64. .not('.MultiFile-applied')
  65. .addClass('MultiFile-applied')
  66. .each(function () {
  67. //#####################################################################
  68. // MAIN PLUGIN FUNCTIONALITY - START
  69. //#####################################################################
  70. // BUG 1251 FIX: http://plugins.jquery.com/project/comments/add/1251
  71. // variable group_count would repeat itself on multiple calls to the plugin.
  72. // this would cause a conflict with multiple elements
  73. // changes scope of variable to global so id will be unique over n calls
  74. window.MultiFile = (window.MultiFile || 0) + 1;
  75. var group_count = window.MultiFile;
  76. // Copy parent attributes - Thanks to Jonas Wagner
  77. // we will use this one to create new input elements
  78. var MultiFile = {
  79. e: this,
  80. E: $(this),
  81. clone: $(this).clone()
  82. };
  83. //===
  84. //# USE CONFIGURATION
  85. var o = $.extend({},
  86. $.fn.MultiFile.options,
  87. options || {}, ($.metadata ? MultiFile.E.metadata() : ($.meta ? MultiFile.E.data() : null)) || {}, /* metadata options */ {} /* internals */
  88. );
  89. // limit number of files that can be selected?
  90. if (!(o.max > 0) /*IsNull(MultiFile.max)*/ ) {
  91. o.max = MultiFile.E.attr('maxlength');
  92. };
  93. if (!(o.max > 0) /*IsNull(MultiFile.max)*/ ) {
  94. o.max = (String(MultiFile.e.className.match(/\b(max|limit)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];
  95. if (!(o.max > 0)) o.max = -1;
  96. else o.max = String(o.max).match(/[0-9]+/gi)[0];
  97. };
  98. o.max = new Number(o.max);
  99. // limit extensions?
  100. o.accept = o.accept || MultiFile.E.attr('accept') || '';
  101. if (!o.accept) {
  102. o.accept = (MultiFile.e.className.match(/\b(accept\-[\w\|]+)\b/gi)) || '';
  103. o.accept = new String(o.accept).replace(/^(accept|ext)\-/i, '');
  104. };
  105. // limit total pay load size
  106. o.maxsize = o.maxsize>0?o.maxsize:null || MultiFile.E.data('maxsize') || 0;
  107. if (!(o.maxsize > 0) /*IsNull(MultiFile.maxsize)*/ ) {
  108. o.maxsize = (String(MultiFile.e.className.match(/\b(maxsize|maxload|size)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];
  109. if (!(o.maxsize > 0)) o.maxsize = -1;
  110. else o.maxsize = String(o.maxsize).match(/[0-9]+/gi)[0];
  111. };
  112. // limit individual file size
  113. o.maxfile = o.maxfile>0?o.maxfile:null || MultiFile.E.data('maxfile') || 0;
  114. if (!(o.maxfile > 0) /*IsNull(MultiFile.maxfile)*/ ) {
  115. o.maxfile = (String(MultiFile.e.className.match(/\b(maxfile|filemax)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];
  116. if (!(o.maxfile > 0)) o.maxfile = -1;
  117. else o.maxfile = String(o.maxfile).match(/[0-9]+/gi)[0];
  118. };
  119. //===
  120. // size options are accepted in kylobytes, so multiple them by 1024
  121. if(o.maxfile>1) o.maxfile = o.maxfile * 1024;
  122. if(o.maxsize>1) o.maxsize = o.maxsize * 1024;
  123. //===
  124. // HTML5: enforce multiple selection to be enabled, except when explicitly disabled
  125. if (o.multiple !== false) {
  126. if (o.max > 1) MultiFile.E.attr('multiple', 'multiple').prop('multiple', true);
  127. }
  128. //===
  129. // APPLY CONFIGURATION
  130. $.extend(MultiFile, o || {});
  131. MultiFile.STRING = $.extend({}, $.fn.MultiFile.options.STRING, MultiFile.STRING);
  132. //===
  133. //#########################################
  134. // PRIVATE PROPERTIES/METHODS
  135. $.extend(MultiFile, {
  136. n: 0, // How many elements are currently selected?
  137. slaves: [],
  138. files: [],
  139. instanceKey: MultiFile.e.id || 'MultiFile' + String(group_count), // Instance Key?
  140. generateID: function (z) {
  141. return MultiFile.instanceKey + (z > 0 ? '_F' + String(z) : '');
  142. },
  143. trigger: function (event, element, MultiFile, files) {
  144. var rv, handler = MultiFile[event] || MultiFile['on'+event] ;
  145. if (handler){
  146. files = files || MultiFile.files || FILE_LIST(this);
  147. ;
  148. $.each(files,function(i, file){
  149. // execute function in element's context, so 'this' variable is current element
  150. rv = handler.apply(MultiFile.wrapper, [element, file.name, MultiFile, file]);
  151. });
  152. return rv;
  153. };
  154. }
  155. });
  156. //===
  157. // Setup dynamic regular expression for extension validation
  158. // - thanks to John-Paul Bader: http://smyck.de/2006/08/11/javascript-dynamic-regular-expresions/
  159. if (String(MultiFile.accept).length > 1) {
  160. MultiFile.accept = MultiFile.accept.replace(/\W+/g, '|').replace(/^\W|\W$/g, '');
  161. MultiFile.rxAccept = new RegExp('\\.(' + (MultiFile.accept ? MultiFile.accept : '') + ')$', 'gi');
  162. };
  163. //===
  164. // Create wrapper to hold our file list
  165. MultiFile.wrapID = MultiFile.instanceKey;// + '_wrap'; // Wrapper ID?
  166. MultiFile.E.wrap('<div class="MultiFile-wrap" id="' + MultiFile.wrapID + '"></div>');
  167. MultiFile.wrapper = $('#' + MultiFile.wrapID + '');
  168. //===
  169. // MultiFile MUST have a name - default: file1[], file2[], file3[]
  170. MultiFile.e.name = MultiFile.e.name || 'file' + group_count + '[]';
  171. //===
  172. if (!MultiFile.list) {
  173. // Create a wrapper for the list
  174. // * OPERA BUG: NO_MODIFICATION_ALLOWED_ERR ('list' is a read-only property)
  175. // this change allows us to keep the files in the order they were selected
  176. MultiFile.wrapper.append('<div class="MultiFile-list" id="' + MultiFile.wrapID + '_list"></div>');
  177. MultiFile.list = $('#' + MultiFile.wrapID + '_list');
  178. };
  179. MultiFile.list = $(MultiFile.list);
  180. //===
  181. // Bind a new element
  182. MultiFile.addSlave = function (slave, slave_count) {
  183. //if(window.console) console.log('MultiFile.addSlave',slave_count);
  184. // Keep track of how many elements have been displayed
  185. MultiFile.n++;
  186. // Add reference to master element
  187. slave.MultiFile = MultiFile;
  188. // BUG FIX: http://plugins.jquery.com/node/1495
  189. // Clear identifying properties from clones
  190. slave.id = slave.name = '';
  191. // Define element's ID and name (upload components need this!)
  192. //slave.id = slave.id || MultiFile.generateID(slave_count);
  193. slave.id = MultiFile.generateID(slave_count);
  194. //FIX for: http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=23
  195. //CHANGE v2.2.1 - change ID of all file elements, keep original ID in wrapper
  196. // 2008-Apr-29: New customizable naming convention (see url below)
  197. // http://groups.google.com/group/jquery-dev/browse_frm/thread/765c73e41b34f924#
  198. slave.name = String(MultiFile.namePattern
  199. /*master name*/
  200. .replace(/\$name/gi, $(MultiFile.clone).attr('name'))
  201. /*master id */
  202. .replace(/\$id/gi, $(MultiFile.clone).attr('id'))
  203. /*group count*/
  204. .replace(/\$g/gi, group_count) //(group_count>0?group_count:''))
  205. /*slave count*/
  206. .replace(/\$i/gi, slave_count) //(slave_count>0?slave_count:''))
  207. );
  208. // If we've reached maximum number, disable input slave
  209. var disable_slave;
  210. if ((MultiFile.max > 0) && ((MultiFile.files.length) > (MultiFile.max))) {
  211. slave.disabled = true;
  212. disable_slave = true;
  213. };
  214. // Remember most recent slave
  215. MultiFile.current = slave;
  216. // We'll use jQuery from now on
  217. slave = $(slave);
  218. // Clear value
  219. slave.val('').attr('value', '')[0].value = '';
  220. // Stop plugin initializing on slaves
  221. slave.addClass('MultiFile-applied');
  222. // Triggered when a file is selected
  223. slave.change(function (a, b, c) {
  224. //if(window.console) console.log('MultiFile.slave.change',slave_count);
  225. //if(window.console) console.log('MultiFile.slave.change',this.files);
  226. // Lose focus to stop IE7 firing onchange again
  227. $(this).blur();
  228. //# NEW 2014-04-14 - accept multiple file selection, HTML5
  229. var e = this,
  230. prevs = MultiFile.files || [],
  231. files = this.files || [{
  232. name: this.value,
  233. size: 0,
  234. type: ((this.value || '').match(/[^\.]+$/i) || [''])[0]
  235. }],
  236. newfs = [],
  237. newfs_size = 0,
  238. total_size = MultiFile.total_size || 0/*,
  239. html5_multi_mode = this.files && $(this).attr('multiple')*/
  240. ;
  241. // recap
  242. //console.log('START '+ prevs.length + ' files @ '+ sl(total_size) +'.', prevs);
  243. //# Retrive value of selected file from element
  244. var ERROR = []; //, v = String(this.value || '');
  245. // make a normal array
  246. $.each(files, function (i, file) {
  247. newfs[newfs.length] = file;
  248. });
  249. //# Trigger Event! onFileSelect
  250. MultiFile.trigger('FileSelect', this, MultiFile, newfs);
  251. //# End Event!
  252. // validate individual files
  253. $.each(files, function (i, file) {
  254. // pop local variables out of array/file object
  255. var v = file.name.replace(/^C:\\fakepath\\/gi,''),
  256. s = file.size,
  257. p = function(z){
  258. return z
  259. .replace('$ext', String(v.match(/[^\.]+$/i) || ''))
  260. .replace('$file', v.match(/[^\/\\]+$/gi))
  261. .replace('$size', sl(s) + ' > ' + sl(MultiFile.maxfile))
  262. }
  263. ;
  264. // check extension
  265. if (MultiFile.accept && v && !v.match(MultiFile.rxAccept)) {
  266. ERROR[ERROR.length] = p(MultiFile.STRING.denied);
  267. MultiFile.trigger('FileInvalid', this, MultiFile, [file]);
  268. };
  269. // Disallow duplicates
  270. $(MultiFile.wrapper).find('input[type=file]').not(e).each(function(){
  271. // go through each file in each slave
  272. $.each(FILE_LIST(this), function (i, file) {
  273. if(file.name){
  274. //console.log('MultiFile.debug> Duplicate?', file.name, v);
  275. var x = (file.name || '').replace(/^C:\\fakepath\\/gi,'');
  276. if ( v == x || v == x.substr(x.length - v.length)) {
  277. ERROR[ERROR.length] = p(MultiFile.STRING.duplicate);
  278. MultiFile.trigger('FileDuplicate', e, MultiFile, [file]);
  279. };
  280. };
  281. });
  282. });
  283. // limit the max size of individual files selected
  284. if (MultiFile.maxfile>0 && s>0 && s>MultiFile.maxfile) {
  285. ERROR[ERROR.length] = p(MultiFile.STRING.toobig);
  286. MultiFile.trigger('FileTooBig', this, MultiFile, [file]);
  287. };
  288. // check extension
  289. var customError = MultiFile.trigger('FileValidate', this, MultiFile, [file]);
  290. if(customError && customError!=''){
  291. ERROR[ERROR.length] = p(customError);
  292. };
  293. // add up size of files selected
  294. newfs_size += file.size;
  295. });
  296. // add up total for all files selected (existing and new)
  297. total_size += newfs_size;
  298. // put some useful information in the file array
  299. newfs.size = newfs_size;
  300. newfs.total = total_size;
  301. newfs.total_length = newfs.length + prevs.length;
  302. // limit the number of files selected
  303. if (MultiFile.max>0 && prevs.length + files.length > MultiFile.max) {
  304. ERROR[ERROR.length] = MultiFile.STRING.toomany.replace('$max', MultiFile.max);
  305. MultiFile.trigger('FileTooMany', this, MultiFile, newfs);
  306. };
  307. // limit the max size of files selected
  308. if (MultiFile.maxsize > 0 && total_size > MultiFile.maxsize) {
  309. ERROR[ERROR.length] = MultiFile.STRING.toomuch.replace('$size', sl(total_size) + ' > ' + sl(MultiFile.maxsize));
  310. MultiFile.trigger('FileTooMuch', this, MultiFile, newfs);
  311. };
  312. // Create a new file input element
  313. var newEle = $(MultiFile.clone).clone(); // Copy parent attributes - Thanks to Jonas Wagner
  314. //# Let's remember which input we've generated so
  315. // we can disable the empty ones before submission
  316. // See: http://plugins.jquery.com/node/1495
  317. newEle.addClass('MultiFile');
  318. // Handle error
  319. if (ERROR.length > 0) {
  320. // Handle error
  321. MultiFile.error(ERROR.join('\n\n'));
  322. // 2007-06-24: BUG FIX - Thanks to Adrian Wróbel <adrian [dot] wrobel [at] gmail.com>
  323. // Ditch the trouble maker and add a fresh new element
  324. MultiFile.n--;
  325. MultiFile.addSlave(newEle[0], slave_count);
  326. slave.parent().prepend(newEle);
  327. slave.remove();
  328. return false;
  329. }
  330. else { // if no errors have been found
  331. // remember total size
  332. MultiFile.total_size = total_size;
  333. // merge arrays
  334. files = prevs.concat(newfs);
  335. // put some useful information in the file array
  336. files.size = total_size;
  337. files.size_label = sl(total_size);
  338. // recap
  339. //console.log('NOW '+ files.length + ' files @ '+ sl(total_size) +'.', files);
  340. // remember files
  341. MultiFile.files = files;
  342. // Hide this element (NB: display:none is evil!)
  343. $(this).css({
  344. position: 'absolute',
  345. top: '-3000px'
  346. });
  347. // Add new element to the form
  348. slave.after(newEle);
  349. // Bind functionality
  350. MultiFile.addSlave(newEle[0], slave_count + 1);
  351. // Update list
  352. MultiFile.addToList(this, slave_count, newfs);
  353. //# Trigger Event! afterFileSelect
  354. MultiFile.trigger('afterFileSelect', this, MultiFile, newfs);
  355. //# End Event!
  356. }; // no errors detected
  357. }); // slave.change()
  358. // point to wrapper
  359. $(slave).data('MultiFile-wrap', MultiFile.wrapper);
  360. // store contorl's settings and file info in wrapper
  361. $(MultiFile.wrapper).data('MultiFile',MultiFile);
  362. // disable?
  363. if(disable_slave) $(slave).attr('disabled','disabled').prop('disabled',true);
  364. }; // MultiFile.addSlave
  365. // Bind a new element
  366. // Add a new file to the list
  367. MultiFile.addToList = function (slave, slave_count, files) {
  368. //if(window.console) console.log('MultiFile.addToList',slave_count);
  369. //# Trigger Event! onFileAppend
  370. MultiFile.trigger('FileAppend', slave, MultiFile, files);
  371. //# End Event!
  372. var names = $('<span/>');
  373. $.each(files, function (i, file) {
  374. var v = String(file.name || '' ).replace(/[&<>'"]/g, function(c) { return '&#'+c.charCodeAt()+';'; }),
  375. S = MultiFile.STRING,
  376. n = S.label || S.file || S.name,
  377. t = S.title || S.tooltip || S.selected,
  378. p = file.type.substr(0,6) == 'image/' ? '<img class="MultiFile-preview" style="'+ MultiFile.previewCss+'"/>' : '',
  379. label = $(
  380. (
  381. '<span class="MultiFile-label" title="' + t + '">'+
  382. '<span class="MultiFile-title">'+ n +'</span>'+
  383. (MultiFile.preview || $(slave).is('.with-preview') ? p : '' )+
  384. '</span>'
  385. )
  386. .replace(/\$(file|name)/gi, (v.match(/[^\/\\]+$/gi)||[v])[0])
  387. .replace(/\$(ext|extension|type)/gi, (v.match(/[^\.]+$/gi)||[''])[0])
  388. .replace(/\$(size)/gi, sl(file.size || 0))
  389. .replace(/\$(preview)/gi, p)
  390. .replace(/\$(i)/gi, i)
  391. );
  392. // now supports preview via locale string.
  393. // just add an <img class='MultiFile-preview'/> anywhere within the "file" string
  394. label.find('img.MultiFile-preview').each(function(){
  395. var t = this;
  396. var oFReader = new FileReader();
  397. oFReader.readAsDataURL(file);
  398. oFReader.onload = function (oFREvent) {
  399. t.src = oFREvent.target.result;
  400. };
  401. });
  402. // append file label to list
  403. if(i>0) names.append(', ');
  404. names.append(label);
  405. var v = String(file.name || '' );
  406. names[names.length] =
  407. (
  408. '<span class="MultiFile-title" title="' + MultiFile.STRING.selected + '">'
  409. + MultiFile.STRING.file +
  410. '</span>'
  411. )
  412. .replace(/\$(file|name)/gi, (v.match(/[^\/\\]+$/gi)||[v])[0])
  413. .replace(/\$(ext|extension|type)/gi, (v.match(/[^\.]+$/gi)||[''])[0])
  414. .replace(/\$(size)/gi, sl(file.size || 0))
  415. .replace(/\$(i)/gi, i)
  416. ;
  417. });
  418. //$.each(files, function (i, file) {
  419. // Create label elements
  420. var
  421. r = $('<div class="MultiFile-label"></div>'),
  422. b = $('<a class="MultiFile-remove" href="#' + MultiFile.wrapID + '">' + MultiFile.STRING.remove + '</a>')
  423. // ********
  424. // TODO:
  425. // refactor this as a single event listener on the control's
  426. // wrapper for better performance and cleaner code
  427. // ********
  428. .click(function () {
  429. // get list of files being removed
  430. var files_being_removed = FILE_LIST(slave);
  431. //# Trigger Event! onFileRemove
  432. MultiFile.trigger('FileRemove', slave, MultiFile, files_being_removed);
  433. //# End Event!
  434. MultiFile.n--;
  435. MultiFile.current.disabled = false;
  436. // remove the relevant <input type="file"/> element
  437. $(slave).remove();
  438. // remove the relevant label
  439. $(this).parent().remove();
  440. // Show most current element again (move into view) and clear selection
  441. $(MultiFile.current).css({
  442. position: '',
  443. top: ''
  444. });
  445. $(MultiFile.current).reset().val('').attr('value', '')[0].value = '';
  446. // point to currently visible element (always true, not necessary)
  447. //MultiFile.current = MultiFile.wrapper.find('[type=file]:visible');
  448. // rebuild array with the files that are left.
  449. var files_remaining = [], remain_size = 0;
  450. // go through each slave
  451. $(MultiFile.wrapper).find('input[type=file]').each(function(){
  452. // go through each file in each slave
  453. $.each(FILE_LIST(this), function (i, file) {
  454. if(file.name){
  455. //console.log('MultiFile.debug> FileRemove> remaining file', file.size, file);
  456. // fresh file array
  457. files_remaining[files_remaining.length] = file;
  458. // fresh size count
  459. remain_size += file.size;
  460. };
  461. });
  462. });
  463. // update MultiFile object
  464. MultiFile.files = files_remaining;
  465. MultiFile.total_size = remain_size;
  466. MultiFile.size_label = sl(remain_size);
  467. // update current control's reference to MultiFile object
  468. $(MultiFile.wrapper).data('MultiFile', MultiFile);
  469. //# Trigger Event! afterFileRemove
  470. MultiFile.trigger('afterFileRemove', slave, MultiFile, files_being_removed);
  471. //# End Event!
  472. //# Trigger Event! onFileChange
  473. MultiFile.trigger('FileChange', MultiFile.current, MultiFile, files_remaining);
  474. //# End Event!
  475. return false;
  476. });
  477. // Insert label
  478. MultiFile.list.append(
  479. r.append(b, ' ', names)
  480. );
  481. //}); // each file?
  482. //# Trigger Event! afterFileAppend
  483. MultiFile.trigger('afterFileAppend', slave, MultiFile, files);
  484. //# End Event!
  485. //# Trigger Event! onFileChange
  486. MultiFile.trigger('FileChange', slave, MultiFile, MultiFile.files);
  487. //# End Event!
  488. }; // MultiFile.addToList
  489. // Add element to selected files list
  490. // Bind functionality to the first element
  491. if (!MultiFile.MultiFile) MultiFile.addSlave(MultiFile.e, 0);
  492. // Increment control count
  493. //MultiFile.I++; // using window.MultiFile
  494. MultiFile.n++;
  495. // deprecated: contorl's data now stored in wrapper because it is never removed.
  496. // improved performance and lower memory comsumption
  497. // Save control to element
  498. //MultiFile.E.data('MultiFile', MultiFile);
  499. //#####################################################################
  500. // MAIN PLUGIN FUNCTIONALITY - END
  501. //#####################################################################
  502. }); // each element
  503. };
  504. /*--------------------------------------------------------*/
  505. /*
  506. ### Core functionality and API ###
  507. */
  508. $.extend($.fn.MultiFile, {
  509. /**
  510. * This method exposes the all the control's data
  511. *
  512. * Returns an object with various settings and properties of the selected files
  513. * for this particular instance of the control. stored in the control's wrapper
  514. *
  515. * @name data
  516. * @type Object
  517. * @cat Plugins/MultiFile
  518. * @author Diego A. (http://www.fyneworks.com/)
  519. *
  520. * @example $('#selector').MultiFile('data');
  521. */
  522. data: function () {
  523. // analyse this element
  524. var e = $(this), b = e.is('.MultiFile-wrap');
  525. // get control wrapper
  526. var wp = b ? e : e.data('MultiFile-wrap');
  527. if(!wp || !wp.length)
  528. return !console.error('Could not find MultiFile control wrapper');
  529. // get control data from wrapper
  530. var mf = wp.data('MultiFile');
  531. if(!mf)
  532. return !console.error('Could not find MultiFile data in wrapper');
  533. // return data
  534. return mf || {};
  535. },
  536. /**
  537. * This method removes all selected files
  538. *
  539. * Returns a jQuery collection of all affected elements.
  540. *
  541. * @name reset
  542. * @type jQuery
  543. * @cat Plugins/MultiFile
  544. * @author Diego A. (http://www.fyneworks.com/)
  545. *
  546. * @example $.fn.MultiFile.reset();
  547. */
  548. reset: function () {
  549. var mf = this.MultiFile('data');
  550. if (mf) $(mf.list).find('a.MultiFile-remove').click();
  551. return $(this);
  552. },
  553. /**
  554. * This method exposes the array of selected files
  555. *
  556. * Returns an array of file objects
  557. *
  558. * @name files
  559. * @type Array
  560. * @cat Plugins/MultiFile
  561. * @author Diego A. (http://www.fyneworks.com/)
  562. *
  563. * @example $('#selector').MultiFile('files');
  564. */
  565. files: function () {
  566. var mf = this.MultiFile('data');
  567. if(!mf) return !console.log('MultiFile plugin not initialized');
  568. return mf.files || [];
  569. },
  570. /**
  571. * This method exposes the plugin's sum of the sizes of all files selected
  572. *
  573. * Returns size (in bytes) of files selected
  574. *
  575. * @name size
  576. * @type Number
  577. * @cat Plugins/MultiFile
  578. * @author Diego A. (http://www.fyneworks.com/)
  579. *
  580. * @example $('#selector').MultiFile('size');
  581. */
  582. size: function () {
  583. var mf = this.MultiFile('data');
  584. if(!mf) return !console.log('MultiFile plugin not initialized');
  585. return mf.total_size || 0;
  586. },
  587. /**
  588. * This method exposes the plugin's tally of how many files have been selected
  589. *
  590. * Returns number (a count) of files selected
  591. *
  592. * @name count
  593. * @type Number
  594. * @cat Plugins/MultiFile
  595. * @author Diego A. (http://www.fyneworks.com/)
  596. *
  597. * @example $('#selector').MultiFile('size');
  598. */
  599. count: function () {
  600. var mf = this.MultiFile('data');
  601. if(!mf) return !console.log('MultiFile plugin not initialized');
  602. return mf.files ? mf.files.length || 0 : 0;
  603. },
  604. /**
  605. * This utility makes it easy to disable all 'empty' file elements in the document before submitting a form.
  606. * It marks the affected elements so they can be easily re-enabled after the form submission or validation.
  607. *
  608. * Returns a jQuery collection of all affected elements.
  609. *
  610. * @name disableEmpty
  611. * @type jQuery
  612. * @cat Plugins/MultiFile
  613. * @author Diego A. (http://www.fyneworks.com/)
  614. *
  615. * @example $.fn.MultiFile.disableEmpty();
  616. * @param String class (optional) A string specifying a class to be applied to all affected elements - Default: 'mfD'.
  617. */
  618. disableEmpty: function (klass) {
  619. klass = (typeof (klass) == 'string' ? klass : '') || 'mfD';
  620. var o = [];
  621. $('input:file.MultiFile').each(function () {
  622. if ($(this).val() == '') o[o.length] = this;
  623. });
  624. // automatically re-enable for novice users
  625. window.clearTimeout($.fn.MultiFile.reEnableTimeout);
  626. $.fn.MultiFile.reEnableTimeout = window.setTimeout($.fn.MultiFile.reEnableEmpty, 500);
  627. return $(o).each(function () {
  628. this.disabled = true
  629. }).addClass(klass);
  630. },
  631. /**
  632. * This method re-enables 'empty' file elements that were disabled (and marked) with the $.fn.MultiFile.disableEmpty method.
  633. *
  634. * Returns a jQuery collection of all affected elements.
  635. *
  636. * @name reEnableEmpty
  637. * @type jQuery
  638. * @cat Plugins/MultiFile
  639. * @author Diego A. (http://www.fyneworks.com/)
  640. *
  641. * @example $.fn.MultiFile.reEnableEmpty();
  642. * @param String klass (optional) A string specifying the class that was used to mark affected elements - Default: 'mfD'.
  643. */
  644. reEnableEmpty: function (klass) {
  645. klass = (typeof (klass) == 'string' ? klass : '') || 'mfD';
  646. return $('input:file.' + klass).removeClass(klass).each(function () {
  647. this.disabled = false
  648. });
  649. },
  650. /**
  651. * This method will intercept other jQuery plugins and disable empty file input elements prior to form submission
  652. *
  653. * @name intercept
  654. * @cat Plugins/MultiFile
  655. * @author Diego A. (http://www.fyneworks.com/)
  656. *
  657. * @example $.fn.MultiFile.intercept();
  658. * @param Array methods (optional) Array of method names to be intercepted
  659. */
  660. intercepted: {},
  661. intercept: function (methods, context, args) {
  662. var method, value;
  663. args = args || [];
  664. if (args.constructor.toString().indexOf("Array") < 0) args = [args];
  665. if (typeof (methods) == 'function') {
  666. $.fn.MultiFile.disableEmpty();
  667. value = methods.apply(context || window, args);
  668. //SEE-http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27
  669. setTimeout(function () {
  670. $.fn.MultiFile.reEnableEmpty()
  671. }, 1000);
  672. return value;
  673. };
  674. if (methods.constructor.toString().indexOf("Array") < 0) methods = [methods];
  675. for (var i = 0; i < methods.length; i++) {
  676. method = methods[i] + ''; // make sure that we have a STRING
  677. if (method)(function (method) { // make sure that method is ISOLATED for the interception
  678. $.fn.MultiFile.intercepted[method] = $.fn[method] || function () {};
  679. $.fn[method] = function () {
  680. $.fn.MultiFile.disableEmpty();
  681. value = $.fn.MultiFile.intercepted[method].apply(this, arguments);
  682. //SEE http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27
  683. setTimeout(function () {
  684. $.fn.MultiFile.reEnableEmpty()
  685. }, 1000);
  686. return value;
  687. }; // interception
  688. })(method); // MAKE SURE THAT method IS ISOLATED for the interception
  689. }; // for each method
  690. } // $.fn.MultiFile.intercept
  691. });
  692. /*--------------------------------------------------------*/
  693. /*
  694. ### Default Settings ###
  695. eg.: You can override default control like this:
  696. $.fn.MultiFile.options.accept = 'gif|jpg';
  697. */
  698. $.fn.MultiFile.options = { //$.extend($.fn.MultiFile, { options: {
  699. accept: '', // accepted file extensions
  700. max: -1, // maximum number of selectable files
  701. maxfile: -1, // maximum size of a single file
  702. maxsize: -1, // maximum size of entire payload
  703. // name to use for newly created elements
  704. namePattern: '$name', // same name by default (which creates an array)
  705. /*master name*/ // use $name
  706. /*master id */ // use $id
  707. /*group count*/ // use $g
  708. /*slave count*/ // use $i
  709. /*other */ // use any combination of he above, eg.: $name_file$i
  710. // previews
  711. preview: false,
  712. previewCss: 'max-height:100px; max-width:100px;',
  713. // STRING: collection lets you show messages in different languages
  714. STRING: {
  715. remove: 'x',
  716. denied: 'You cannot select a $ext file.\nTry again...',
  717. file: '$file',
  718. selected: 'File selected: $file',
  719. duplicate: 'This file has already been selected:\n$file',
  720. toomuch: 'The files selected exceed the maximum size permited ($size)',
  721. toomany: 'Too many files selected (max: $max)',
  722. toobig: '$file is too big (max $size)'
  723. },
  724. // name of methods that should be automcatically intercepted so the plugin can disable
  725. // extra file elements that are empty before execution and automatically re-enable them afterwards
  726. autoIntercept: ['submit', 'ajaxSubmit', 'ajaxForm', 'validate', 'valid' /* array of methods to intercept */ ],
  727. // error handling function
  728. error: function (s) {
  729. if(typeof console != 'undefined') console.log(s);
  730. // TODO: add various dialog handlers here?
  731. alert(s);
  732. }
  733. }; //} });
  734. /*--------------------------------------------------------*/
  735. /*
  736. ### Additional Methods ###
  737. Required functionality outside the plugin's scope
  738. */
  739. // Native input reset method - because this alone doesn't always work: $(element).val('').attr('value', '')[0].value = '';
  740. $.fn.reset = $.fn.reset || function () {
  741. return this.each(function () {
  742. try {
  743. this.reset();
  744. } catch (e) {}
  745. });
  746. };
  747. /*--------------------------------------------------------*/
  748. /*
  749. ### Default implementation ###
  750. The plugin will attach itself to file inputs
  751. with the class 'multi' when the page loads
  752. */
  753. $(function () {
  754. //$("input:file.multi").MultiFile();
  755. $("input[type=file].multi").MultiFile();
  756. });
  757. /*# AVOID COLLISIONS #*/
  758. })(jQuery);
  759. /*# AVOID COLLISIONS #*/