jquery.plupload.queue.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /**
  2. * jquery.plupload.queue.js
  3. *
  4. * Copyright 2009, Moxiecode Systems AB
  5. * Released under GPL License.
  6. *
  7. * License: http://www.plupload.com/license
  8. * Contributing: http://www.plupload.com/contributing
  9. */
  10. /* global jQuery:true, alert:true */
  11. /**
  12. jQuery based implementation of the Plupload API - multi-runtime file uploading API.
  13. To use the widget you must include _jQuery_. It is not meant to be extended in any way and is provided to be
  14. used as it is.
  15. @example
  16. <!-- Instantiating: -->
  17. <div id="uploader">
  18. <p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
  19. </div>
  20. <script>
  21. $('#uploader').pluploadQueue({
  22. url : '../upload.php',
  23. filters : [
  24. {title : "Image files", extensions : "jpg,gif,png"}
  25. ],
  26. rename: true,
  27. flash_swf_url : '../../js/Moxie.swf',
  28. silverlight_xap_url : '../../js/Moxie.xap',
  29. });
  30. </script>
  31. @example
  32. // Retrieving a reference to plupload.Uploader object
  33. var uploader = $('#uploader').pluploadQueue();
  34. uploader.bind('FilesAdded', function() {
  35. // Autostart
  36. setTimeout(uploader.start, 1); // "detach" from the main thread
  37. });
  38. @class pluploadQueue
  39. @constructor
  40. @param {Object} settings For detailed information about each option check documentation.
  41. @param {String} settings.url URL of the server-side upload handler.
  42. @param {Number|String} [settings.chunk_size=0] Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. `e.g. 204800 or "204800b" or "200kb"`. By default - disabled.
  43. @param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message.
  44. @param {Array} [settings.filters=[]] Set of file type filters, each one defined by hash of title and extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR`
  45. @param {String} [settings.flash_swf_url] URL of the Flash swf.
  46. @param {Object} [settings.headers] Custom headers to send with the upload. Hash of name/value pairs.
  47. @param {Number|String} [settings.max_file_size] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`.
  48. @param {Number} [settings.max_retries=0] How many times to retry the chunk or file, before triggering Error event.
  49. @param {Boolean} [settings.multipart=true] Whether to send file and additional parameters as Multipart formated message.
  50. @param {Object} [settings.multipart_params] Hash of key/value pairs to send with every file upload.
  51. @param {Boolean} [settings.multi_selection=true] Enable ability to select multiple files at once in file dialog.
  52. @param {Boolean} [settings.prevent_duplicates=false] Do not let duplicates into the queue. Dispatches `plupload.FILE_DUPLICATE_ERROR`.
  53. @param {String|Object} [settings.required_features] Either comma-separated list or hash of required features that chosen runtime should absolutely possess.
  54. @param {Object} [settings.resize] Enable resizng of images on client-side. Applies to `image/jpeg` and `image/png` only. `e.g. {width : 200, height : 200, quality : 90, crop: true}`
  55. @param {Number} [settings.resize.width] If image is bigger, it will be resized.
  56. @param {Number} [settings.resize.height] If image is bigger, it will be resized.
  57. @param {Number} [settings.resize.quality=90] Compression quality for jpegs (1-100).
  58. @param {Boolean} [settings.resize.crop=false] Whether to crop images to exact dimensions. By default they will be resized proportionally.
  59. @param {String} [settings.runtimes="html5,flash,silverlight,html4"] Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails.
  60. @param {String} [settings.silverlight_xap_url] URL of the Silverlight xap.
  61. @param {Boolean} [settings.unique_names=false] If true will generate unique filenames for uploaded files.
  62. @param {Boolean} [settings.dragdrop=true] Enable ability to add file to the queue by drag'n'dropping them from the desktop.
  63. @param {Boolean} [settings.rename=false] Enable ability to rename files in the queue.
  64. @param {Boolean} [settings.multiple_queues=true] Re-activate the widget after each upload procedure.
  65. */
  66. (function($) {
  67. var uploaders = {};
  68. function _(str) {
  69. return plupload.translate(str) || str;
  70. }
  71. function renderUI(id, target) {
  72. // Remove all existing non plupload items
  73. target.contents().each(function(i, node) {
  74. node = $(node);
  75. if (!node.is('.plupload')) {
  76. node.remove();
  77. }
  78. });
  79. target.prepend(
  80. '<div class="plupload_wrapper plupload_scroll">' +
  81. '<div id="' + id + '_container" class="plupload_container">' +
  82. '<div class="plupload">' +
  83. '<div class="plupload_header">' +
  84. '<div class="plupload_header_content">' +
  85. '<div class="plupload_header_title">' + _('Select files') + '</div>' +
  86. '<div class="plupload_header_text">' + _('Add files to the upload queue and click the start button.') + '</div>' +
  87. '</div>' +
  88. '</div>' +
  89. '<div class="plupload_content">' +
  90. '<div class="plupload_filelist_header">' +
  91. '<div class="plupload_file_name">' + _('Filename') + '</div>' +
  92. '<div class="plupload_file_action">&nbsp;</div>' +
  93. '<div class="plupload_file_status"><span>' + _('Status') + '</span></div>' +
  94. '<div class="plupload_file_size">' + _('Size') + '</div>' +
  95. '<div class="plupload_clearer">&nbsp;</div>' +
  96. '</div>' +
  97. '<ul id="' + id + '_filelist" class="plupload_filelist"></ul>' +
  98. '<div class="plupload_filelist_footer">' +
  99. '<div class="plupload_file_name">' +
  100. '<div class="plupload_buttons">' +
  101. '<a href="#" class="plupload_button plupload_add" id="' + id + '_browse">' + _('Add Files') + '</a>' +
  102. '<a href="#" class="plupload_button plupload_start">' + _('Start Upload') + '</a>' +
  103. '</div>' +
  104. '<span class="plupload_upload_status"></span>' +
  105. '</div>' +
  106. '<div class="plupload_file_action"></div>' +
  107. '<div class="plupload_file_status"><span class="plupload_total_status">0%</span></div>' +
  108. '<div class="plupload_file_size"><span class="plupload_total_file_size">0 b</span></div>' +
  109. '<div class="plupload_progress">' +
  110. '<div class="plupload_progress_container">' +
  111. '<div class="plupload_progress_bar"></div>' +
  112. '</div>' +
  113. '</div>' +
  114. '<div class="plupload_clearer">&nbsp;</div>' +
  115. '</div>' +
  116. '</div>' +
  117. '</div>' +
  118. '</div>' +
  119. '<input type="hidden" id="' + id + '_count" name="' + id + '_count" value="0" />' +
  120. '</div>'
  121. );
  122. }
  123. $.fn.pluploadQueue = function(settings) {
  124. if (settings) {
  125. this.each(function() {
  126. var uploader, target, id, contents_bak;
  127. target = $(this);
  128. id = target.attr('id');
  129. if (!id) {
  130. id = plupload.guid();
  131. target.attr('id', id);
  132. }
  133. contents_bak = target.html();
  134. renderUI(id, target);
  135. uploader = new plupload.Uploader($.extend({
  136. dragdrop : true,
  137. browse_button : id + '_browse',
  138. container : id
  139. }, settings));
  140. uploaders[id] = uploader;
  141. function handleStatus(file) {
  142. var actionClass;
  143. if (file.status == plupload.DONE) {
  144. actionClass = 'plupload_done';
  145. }
  146. if (file.status == plupload.FAILED) {
  147. actionClass = 'plupload_failed';
  148. }
  149. if (file.status == plupload.QUEUED) {
  150. actionClass = 'plupload_delete';
  151. }
  152. if (file.status == plupload.UPLOADING) {
  153. actionClass = 'plupload_uploading';
  154. }
  155. var icon = $('#' + file.id).attr('class', actionClass).find('a').css('display', 'block');
  156. if (file.hint) {
  157. icon.attr('title', file.hint);
  158. }
  159. }
  160. function updateTotalProgress() {
  161. $('span.plupload_total_status', target).html(uploader.total.percent + '%');
  162. $('div.plupload_progress_bar', target).css('width', uploader.total.percent + '%');
  163. $('span.plupload_upload_status', target).html(
  164. _('Uploaded %d/%d files').replace(/%d\/%d/, uploader.total.uploaded+'/'+uploader.files.length)
  165. );
  166. }
  167. function updateList() {
  168. var fileList = $('ul.plupload_filelist', target).html(''), inputCount = 0, inputHTML;
  169. $.each(uploader.files, function(i, file) {
  170. inputHTML = '';
  171. if (file.status == plupload.DONE) {
  172. if (file.target_name) {
  173. inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_tmpname" value="' + plupload.xmlEncode(file.target_name) + '" />';
  174. }
  175. inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_name" value="' + plupload.xmlEncode(file.name) + '" />';
  176. inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_status" value="' + (file.status == plupload.DONE ? 'done' : 'failed') + '" />';
  177. inputCount++;
  178. $('#' + id + '_count').val(inputCount);
  179. }
  180. fileList.append(
  181. '<li id="' + file.id + '">' +
  182. '<div class="plupload_file_name"><span>' + file.name + '</span></div>' +
  183. '<div class="plupload_file_action"><a href="#"></a></div>' +
  184. '<div class="plupload_file_status">' + file.percent + '%</div>' +
  185. '<div class="plupload_file_size">' + plupload.formatSize(file.size) + '</div>' +
  186. '<div class="plupload_clearer">&nbsp;</div>' +
  187. inputHTML +
  188. '</li>'
  189. );
  190. handleStatus(file);
  191. $('#' + file.id + '.plupload_delete a').click(function(e) {
  192. $('#' + file.id).remove();
  193. uploader.removeFile(file);
  194. e.preventDefault();
  195. });
  196. });
  197. $('span.plupload_total_file_size', target).html(plupload.formatSize(uploader.total.size));
  198. if (uploader.total.queued === 0) {
  199. $('span.plupload_add_text', target).html(_('Add Files'));
  200. } else {
  201. $('span.plupload_add_text', target).html(_('%d files queued').replace(/%d/, uploader.total.queued));
  202. }
  203. $('a.plupload_start', target).toggleClass('plupload_disabled', uploader.files.length == (uploader.total.uploaded + uploader.total.failed));
  204. // Scroll to end of file list
  205. fileList[0].scrollTop = fileList[0].scrollHeight;
  206. updateTotalProgress();
  207. // Re-add drag message if there is no files
  208. if (!uploader.files.length && uploader.features.dragdrop && uploader.settings.dragdrop) {
  209. $('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>');
  210. }
  211. }
  212. function destroy() {
  213. delete uploaders[id];
  214. uploader.destroy();
  215. target.html(contents_bak);
  216. uploader = target = contents_bak = null;
  217. }
  218. uploader.bind("UploadFile", function(up, file) {
  219. $('#' + file.id).addClass('plupload_current_file');
  220. });
  221. uploader.bind('Init', function(up, res) {
  222. // Enable rename support
  223. if (!settings.unique_names && settings.rename) {
  224. target.on('click', '#' + id + '_filelist div.plupload_file_name span', function(e) {
  225. var targetSpan = $(e.target), file, parts, name, ext = "";
  226. // Get file name and split out name and extension
  227. file = up.getFile(targetSpan.parents('li')[0].id);
  228. name = file.name;
  229. parts = /^(.+)(\.[^.]+)$/.exec(name);
  230. if (parts) {
  231. name = parts[1];
  232. ext = parts[2];
  233. }
  234. // Display input element
  235. targetSpan.hide().after('<input type="text" />');
  236. targetSpan.next().val(name).focus().blur(function() {
  237. targetSpan.show().next().remove();
  238. }).keydown(function(e) {
  239. var targetInput = $(this);
  240. if (e.keyCode == 13) {
  241. e.preventDefault();
  242. // Rename file and glue extension back on
  243. file.name = targetInput.val() + ext;
  244. targetSpan.html(file.name);
  245. targetInput.blur();
  246. }
  247. });
  248. });
  249. }
  250. // Enable drag/drop (see PostInit handler as well)
  251. if (up.settings.dragdrop) {
  252. up.settings.drop_element = id + '_filelist';
  253. }
  254. $('#' + id + '_container').attr('title', 'Using runtime: ' + res.runtime);
  255. $('a.plupload_start', target).click(function(e) {
  256. if (!$(this).hasClass('plupload_disabled')) {
  257. uploader.start();
  258. }
  259. e.preventDefault();
  260. });
  261. $('a.plupload_stop', target).click(function(e) {
  262. e.preventDefault();
  263. uploader.stop();
  264. });
  265. $('a.plupload_start', target).addClass('plupload_disabled');
  266. });
  267. uploader.bind("Error", function(up, err) {
  268. var file = err.file, message;
  269. if (file) {
  270. message = err.message;
  271. if (err.details) {
  272. message += " (" + err.details + ")";
  273. }
  274. if (err.code == plupload.FILE_SIZE_ERROR) {
  275. alert(_("Error: File too large:") + " " + file.name);
  276. }
  277. if (err.code == plupload.FILE_EXTENSION_ERROR) {
  278. alert(_("Error: Invalid file extension:") + " " + file.name);
  279. }
  280. file.hint = message;
  281. $('#' + file.id).attr('class', 'plupload_failed').find('a').css('display', 'block').attr('title', message);
  282. }
  283. if (err.code === plupload.INIT_ERROR) {
  284. setTimeout(function() {
  285. destroy();
  286. }, 1);
  287. }
  288. });
  289. uploader.bind("PostInit", function(up) {
  290. // features are populated only after input components are fully instantiated
  291. if (up.settings.dragdrop && up.features.dragdrop) {
  292. $('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>');
  293. }
  294. });
  295. uploader.init();
  296. uploader.bind('StateChanged', function() {
  297. if (uploader.state === plupload.STARTED) {
  298. $('li.plupload_delete a,div.plupload_buttons', target).hide();
  299. $('span.plupload_upload_status,div.plupload_progress,a.plupload_stop', target).css('display', 'block');
  300. $('span.plupload_upload_status', target).html('Uploaded ' + uploader.total.uploaded + '/' + uploader.files.length + ' files');
  301. if (settings.multiple_queues) {
  302. $('span.plupload_total_status,span.plupload_total_file_size', target).show();
  303. }
  304. } else {
  305. updateList();
  306. $('a.plupload_stop,div.plupload_progress', target).hide();
  307. $('a.plupload_delete', target).css('display', 'block');
  308. if (settings.multiple_queues && uploader.total.uploaded + uploader.total.failed == uploader.files.length) {
  309. $(".plupload_buttons,.plupload_upload_status", target).css("display", "inline");
  310. $(".plupload_start", target).addClass("plupload_disabled");
  311. $('span.plupload_total_status,span.plupload_total_file_size', target).hide();
  312. }
  313. }
  314. });
  315. uploader.bind('QueueChanged', updateList);
  316. uploader.bind('FileUploaded', function(up, file) {
  317. handleStatus(file);
  318. });
  319. uploader.bind("UploadProgress", function(up, file) {
  320. // Set file specific progress
  321. $('#' + file.id + ' div.plupload_file_status', target).html(file.percent + '%');
  322. handleStatus(file);
  323. updateTotalProgress();
  324. });
  325. // Call setup function
  326. if (settings.setup) {
  327. settings.setup(uploader);
  328. }
  329. });
  330. return this;
  331. } else {
  332. // Get uploader instance for specified element
  333. return uploaders[$(this[0]).attr('id')];
  334. }
  335. };
  336. })(jQuery);