jquery.plupload.queue.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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($, o) {
  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. settings = $.extend({
  136. dragdrop : true,
  137. browse_button : id + '_browse',
  138. container : id
  139. }, settings);
  140. // Enable drag/drop (see PostInit handler as well)
  141. if (settings.dragdrop) {
  142. settings.drop_element = id + '_filelist';
  143. }
  144. uploader = new plupload.Uploader(settings);
  145. uploaders[id] = uploader;
  146. function handleStatus(file) {
  147. var actionClass;
  148. if (file.status == plupload.DONE) {
  149. actionClass = 'plupload_done';
  150. }
  151. if (file.status == plupload.FAILED) {
  152. actionClass = 'plupload_failed';
  153. }
  154. if (file.status == plupload.QUEUED) {
  155. actionClass = 'plupload_delete';
  156. }
  157. if (file.status == plupload.UPLOADING) {
  158. actionClass = 'plupload_uploading';
  159. }
  160. var icon = $('#' + file.id).attr('class', actionClass).find('a').css('display', 'block');
  161. if (file.hint) {
  162. icon.attr('title', file.hint);
  163. }
  164. }
  165. function updateTotalProgress() {
  166. $('span.plupload_total_status', target).html(uploader.total.percent + '%');
  167. $('div.plupload_progress_bar', target).css('width', uploader.total.percent + '%');
  168. $('span.plupload_upload_status', target).html(
  169. o.sprintf(_('Uploaded %d/%d files'), uploader.total.uploaded, uploader.files.length)
  170. );
  171. }
  172. function updateList() {
  173. var fileList = $('ul.plupload_filelist', target).html(''), inputCount = 0, inputHTML;
  174. $.each(uploader.files, function(i, file) {
  175. inputHTML = '';
  176. if (file.status == plupload.DONE) {
  177. if (file.target_name) {
  178. inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_tmpname" value="' + plupload.xmlEncode(file.target_name) + '" />';
  179. }
  180. inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_name" value="' + plupload.xmlEncode(file.name) + '" />';
  181. inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_status" value="' + (file.status == plupload.DONE ? 'done' : 'failed') + '" />';
  182. inputCount++;
  183. $('#' + id + '_count').val(inputCount);
  184. }
  185. fileList.append(
  186. '<li id="' + file.id + '">' +
  187. '<div class="plupload_file_name"><span>' + file.name + '</span></div>' +
  188. '<div class="plupload_file_action"><a href="#"></a></div>' +
  189. '<div class="plupload_file_status">' + file.percent + '%</div>' +
  190. '<div class="plupload_file_size">' + plupload.formatSize(file.size) + '</div>' +
  191. '<div class="plupload_clearer">&nbsp;</div>' +
  192. inputHTML +
  193. '</li>'
  194. );
  195. handleStatus(file);
  196. $('#' + file.id + '.plupload_delete a').click(function(e) {
  197. $('#' + file.id).remove();
  198. uploader.removeFile(file);
  199. e.preventDefault();
  200. });
  201. });
  202. $('span.plupload_total_file_size', target).html(plupload.formatSize(uploader.total.size));
  203. if (uploader.total.queued === 0) {
  204. $('span.plupload_add_text', target).html(_('Add Files'));
  205. } else {
  206. $('span.plupload_add_text', target).html(o.sprintf(_('%d files queued'), uploader.total.queued));
  207. }
  208. $('a.plupload_start', target).toggleClass('plupload_disabled', uploader.files.length == (uploader.total.uploaded + uploader.total.failed));
  209. // Scroll to end of file list
  210. fileList[0].scrollTop = fileList[0].scrollHeight;
  211. updateTotalProgress();
  212. // Re-add drag message if there is no files
  213. if (!uploader.files.length && uploader.features.dragdrop && uploader.settings.dragdrop) {
  214. $('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>');
  215. }
  216. }
  217. function destroy() {
  218. delete uploaders[id];
  219. uploader.destroy();
  220. target.html(contents_bak);
  221. uploader = target = contents_bak = null;
  222. }
  223. uploader.bind("UploadFile", function(up, file) {
  224. $('#' + file.id).addClass('plupload_current_file');
  225. });
  226. uploader.bind('Init', function(up, res) {
  227. // Enable rename support
  228. if (!settings.unique_names && settings.rename) {
  229. target.on('click', '#' + id + '_filelist div.plupload_file_name span', function(e) {
  230. var targetSpan = $(e.target), file, parts, name, ext = "";
  231. // Get file name and split out name and extension
  232. file = up.getFile(targetSpan.parents('li')[0].id);
  233. name = file.name;
  234. parts = /^(.+)(\.[^.]+)$/.exec(name);
  235. if (parts) {
  236. name = parts[1];
  237. ext = parts[2];
  238. }
  239. // Display input element
  240. targetSpan.hide().after('<input type="text" />');
  241. targetSpan.next().val(name).focus().blur(function() {
  242. targetSpan.show().next().remove();
  243. }).keydown(function(e) {
  244. var targetInput = $(this);
  245. if (e.keyCode == 13) {
  246. e.preventDefault();
  247. // Rename file and glue extension back on
  248. file.name = targetInput.val() + ext;
  249. targetSpan.html(file.name);
  250. targetInput.blur();
  251. }
  252. });
  253. });
  254. }
  255. $('#' + id + '_container').attr('title', 'Using runtime: ' + res.runtime);
  256. $('a.plupload_start', target).click(function(e) {
  257. if (!$(this).hasClass('plupload_disabled')) {
  258. uploader.start();
  259. }
  260. e.preventDefault();
  261. });
  262. $('a.plupload_stop', target).click(function(e) {
  263. e.preventDefault();
  264. uploader.stop();
  265. });
  266. $('a.plupload_start', target).addClass('plupload_disabled');
  267. });
  268. uploader.bind("Error", function(up, err) {
  269. var file = err.file, message;
  270. if (file) {
  271. message = err.message;
  272. if (err.details) {
  273. message += " (" + err.details + ")";
  274. }
  275. if (err.code == plupload.FILE_SIZE_ERROR) {
  276. alert(_("Error: File too large:") + " " + file.name);
  277. }
  278. if (err.code == plupload.FILE_EXTENSION_ERROR) {
  279. alert(_("Error: Invalid file extension:") + " " + file.name);
  280. }
  281. file.hint = message;
  282. $('#' + file.id).attr('class', 'plupload_failed').find('a').css('display', 'block').attr('title', message);
  283. }
  284. if (err.code === plupload.INIT_ERROR) {
  285. setTimeout(function() {
  286. destroy();
  287. }, 1);
  288. }
  289. });
  290. uploader.bind("PostInit", function(up) {
  291. // features are populated only after input components are fully instantiated
  292. if (up.settings.dragdrop && up.features.dragdrop) {
  293. $('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>');
  294. }
  295. });
  296. uploader.init();
  297. uploader.bind('StateChanged', function() {
  298. if (uploader.state === plupload.STARTED) {
  299. $('li.plupload_delete a,div.plupload_buttons', target).hide();
  300. uploader.disableBrowse(true);
  301. $('span.plupload_upload_status,div.plupload_progress,a.plupload_stop', target).css('display', 'block');
  302. $('span.plupload_upload_status', target).html('Uploaded ' + uploader.total.uploaded + '/' + uploader.files.length + ' files');
  303. if (settings.multiple_queues) {
  304. $('span.plupload_total_status,span.plupload_total_file_size', target).show();
  305. }
  306. } else {
  307. updateList();
  308. $('a.plupload_stop,div.plupload_progress', target).hide();
  309. $('a.plupload_delete', target).css('display', 'block');
  310. if (settings.multiple_queues && uploader.total.uploaded + uploader.total.failed == uploader.files.length) {
  311. $(".plupload_buttons,.plupload_upload_status", target).css("display", "inline");
  312. uploader.disableBrowse(false);
  313. $(".plupload_start", target).addClass("plupload_disabled");
  314. $('span.plupload_total_status,span.plupload_total_file_size', target).hide();
  315. }
  316. }
  317. });
  318. uploader.bind('FilesAdded', updateList);
  319. uploader.bind('FilesRemoved', function() {
  320. // since the whole file list is redrawn for every change in the queue
  321. // we need to scroll back to the file removal point to avoid annoying
  322. // scrolling to the bottom bug (see #926)
  323. var scrollTop = $('#' + id + '_filelist').scrollTop();
  324. updateList();
  325. $('#' + id + '_filelist').scrollTop(scrollTop);
  326. });
  327. uploader.bind('FileUploaded', function(up, file) {
  328. handleStatus(file);
  329. });
  330. uploader.bind("UploadProgress", function(up, file) {
  331. // Set file specific progress
  332. $('#' + file.id + ' div.plupload_file_status', target).html(file.percent + '%');
  333. handleStatus(file);
  334. updateTotalProgress();
  335. });
  336. // Call setup function
  337. if (settings.setup) {
  338. settings.setup(uploader);
  339. }
  340. });
  341. return this;
  342. } else {
  343. // Get uploader instance for specified element
  344. return uploaders[$(this[0]).attr('id')];
  345. }
  346. };
  347. })(jQuery, mOxie);