jquery.fileupload.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. /*
  2. * jQuery File Upload Plugin 5.19.7
  3. * https://github.com/blueimp/jQuery-File-Upload
  4. *
  5. * Copyright 2010, Sebastian Tschan
  6. * https://blueimp.net
  7. *
  8. * Licensed under the MIT license:
  9. * http://www.opensource.org/licenses/MIT
  10. */
  11. /*jslint nomen: true, unparam: true, regexp: true */
  12. /*global define, window, document, File, Blob, FormData, location */
  13. (function (factory) {
  14. 'use strict';
  15. if (typeof define === 'function' && define.amd) {
  16. // Register as an anonymous AMD module:
  17. define([
  18. 'jquery',
  19. 'jquery.ui.widget'
  20. ], factory);
  21. } else {
  22. // Browser globals:
  23. factory(window.jQuery);
  24. }
  25. }(function ($) {
  26. 'use strict';
  27. // The FileReader API is not actually used, but works as feature detection,
  28. // as e.g. Safari supports XHR file uploads via the FormData API,
  29. // but not non-multipart XHR file uploads:
  30. $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
  31. $.support.xhrFormDataFileUpload = !!window.FormData;
  32. // The fileupload widget listens for change events on file input fields defined
  33. // via fileInput setting and paste or drop events of the given dropZone.
  34. // In addition to the default jQuery Widget methods, the fileupload widget
  35. // exposes the "add" and "send" methods, to add or directly send files using
  36. // the fileupload API.
  37. // By default, files added via file input selection, paste, drag & drop or
  38. // "add" method are uploaded immediately, but it is possible to override
  39. // the "add" callback option to queue file uploads.
  40. $.widget('blueimp.fileupload', {
  41. options: {
  42. // The drop target element(s), by the default the complete document.
  43. // Set to null to disable drag & drop support:
  44. dropZone: $(document),
  45. // The paste target element(s), by the default the complete document.
  46. // Set to null to disable paste support:
  47. pasteZone: $(document),
  48. // The file input field(s), that are listened to for change events.
  49. // If undefined, it is set to the file input fields inside
  50. // of the widget element on plugin initialization.
  51. // Set to null to disable the change listener.
  52. fileInput: undefined,
  53. // By default, the file input field is replaced with a clone after
  54. // each input field change event. This is required for iframe transport
  55. // queues and allows change events to be fired for the same file
  56. // selection, but can be disabled by setting the following option to false:
  57. replaceFileInput: true,
  58. // The parameter name for the file form data (the request argument name).
  59. // If undefined or empty, the name property of the file input field is
  60. // used, or "files[]" if the file input name property is also empty,
  61. // can be a string or an array of strings:
  62. paramName: undefined,
  63. // By default, each file of a selection is uploaded using an individual
  64. // request for XHR type uploads. Set to false to upload file
  65. // selections in one request each:
  66. singleFileUploads: true,
  67. // To limit the number of files uploaded with one XHR request,
  68. // set the following option to an integer greater than 0:
  69. limitMultiFileUploads: undefined,
  70. // Set the following option to true to issue all file upload requests
  71. // in a sequential order:
  72. sequentialUploads: false,
  73. // To limit the number of concurrent uploads,
  74. // set the following option to an integer greater than 0:
  75. limitConcurrentUploads: undefined,
  76. // Set the following option to true to force iframe transport uploads:
  77. forceIframeTransport: false,
  78. // Set the following option to the location of a redirect url on the
  79. // origin server, for cross-domain iframe transport uploads:
  80. redirect: undefined,
  81. // The parameter name for the redirect url, sent as part of the form
  82. // data and set to 'redirect' if this option is empty:
  83. redirectParamName: undefined,
  84. // Set the following option to the location of a postMessage window,
  85. // to enable postMessage transport uploads:
  86. postMessage: undefined,
  87. // By default, XHR file uploads are sent as multipart/form-data.
  88. // The iframe transport is always using multipart/form-data.
  89. // Set to false to enable non-multipart XHR uploads:
  90. multipart: true,
  91. // To upload large files in smaller chunks, set the following option
  92. // to a preferred maximum chunk size. If set to 0, null or undefined,
  93. // or the browser does not support the required Blob API, files will
  94. // be uploaded as a whole.
  95. maxChunkSize: undefined,
  96. // When a non-multipart upload or a chunked multipart upload has been
  97. // aborted, this option can be used to resume the upload by setting
  98. // it to the size of the already uploaded bytes. This option is most
  99. // useful when modifying the options object inside of the "add" or
  100. // "send" callbacks, as the options are cloned for each file upload.
  101. uploadedBytes: undefined,
  102. // By default, failed (abort or error) file uploads are removed from the
  103. // global progress calculation. Set the following option to false to
  104. // prevent recalculating the global progress data:
  105. recalculateProgress: true,
  106. // Interval in milliseconds to calculate and trigger progress events:
  107. progressInterval: 100,
  108. // Interval in milliseconds to calculate progress bitrate:
  109. bitrateInterval: 500,
  110. // Additional form data to be sent along with the file uploads can be set
  111. // using this option, which accepts an array of objects with name and
  112. // value properties, a function returning such an array, a FormData
  113. // object (for XHR file uploads), or a simple object.
  114. // The form of the first fileInput is given as parameter to the function:
  115. formData: function (form) {
  116. return form.serializeArray();
  117. },
  118. // The add callback is invoked as soon as files are added to the fileupload
  119. // widget (via file input selection, drag & drop, paste or add API call).
  120. // If the singleFileUploads option is enabled, this callback will be
  121. // called once for each file in the selection for XHR file uplaods, else
  122. // once for each file selection.
  123. // The upload starts when the submit method is invoked on the data parameter.
  124. // The data object contains a files property holding the added files
  125. // and allows to override plugin options as well as define ajax settings.
  126. // Listeners for this callback can also be bound the following way:
  127. // .bind('fileuploadadd', func);
  128. // data.submit() returns a Promise object and allows to attach additional
  129. // handlers using jQuery's Deferred callbacks:
  130. // data.submit().done(func).fail(func).always(func);
  131. add: function (e, data) {
  132. data.submit();
  133. },
  134. // Other callbacks:
  135. // Callback for the submit event of each file upload:
  136. // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
  137. // Callback for the start of each file upload request:
  138. // send: function (e, data) {}, // .bind('fileuploadsend', func);
  139. // Callback for successful uploads:
  140. // done: function (e, data) {}, // .bind('fileuploaddone', func);
  141. // Callback for failed (abort or error) uploads:
  142. // fail: function (e, data) {}, // .bind('fileuploadfail', func);
  143. // Callback for completed (success, abort or error) requests:
  144. // always: function (e, data) {}, // .bind('fileuploadalways', func);
  145. // Callback for upload progress events:
  146. // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
  147. // Callback for global upload progress events:
  148. // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
  149. // Callback for uploads start, equivalent to the global ajaxStart event:
  150. // start: function (e) {}, // .bind('fileuploadstart', func);
  151. // Callback for uploads stop, equivalent to the global ajaxStop event:
  152. // stop: function (e) {}, // .bind('fileuploadstop', func);
  153. // Callback for change events of the fileInput(s):
  154. // change: function (e, data) {}, // .bind('fileuploadchange', func);
  155. // Callback for paste events to the pasteZone(s):
  156. // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
  157. // Callback for drop events of the dropZone(s):
  158. // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
  159. // Callback for dragover events of the dropZone(s):
  160. // dragover: function (e) {}, // .bind('fileuploaddragover', func);
  161. // The plugin options are used as settings object for the ajax calls.
  162. // The following are jQuery ajax settings required for the file uploads:
  163. processData: false,
  164. contentType: false,
  165. cache: false
  166. },
  167. // A list of options that require a refresh after assigning a new value:
  168. _refreshOptionsList: [
  169. 'fileInput',
  170. 'dropZone',
  171. 'pasteZone',
  172. 'multipart',
  173. 'forceIframeTransport'
  174. ],
  175. _BitrateTimer: function () {
  176. this.timestamp = +(new Date());
  177. this.loaded = 0;
  178. this.bitrate = 0;
  179. this.getBitrate = function (now, loaded, interval) {
  180. var timeDiff = now - this.timestamp;
  181. if (!this.bitrate || !interval || timeDiff > interval) {
  182. this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
  183. this.loaded = loaded;
  184. this.timestamp = now;
  185. }
  186. return this.bitrate;
  187. };
  188. },
  189. _isXHRUpload: function (options) {
  190. return !options.forceIframeTransport &&
  191. ((!options.multipart && $.support.xhrFileUpload) ||
  192. $.support.xhrFormDataFileUpload);
  193. },
  194. _getFormData: function (options) {
  195. var formData;
  196. if (typeof options.formData === 'function') {
  197. return options.formData(options.form);
  198. }
  199. if ($.isArray(options.formData)) {
  200. return options.formData;
  201. }
  202. if (options.formData) {
  203. formData = [];
  204. $.each(options.formData, function (name, value) {
  205. formData.push({name: name, value: value});
  206. });
  207. return formData;
  208. }
  209. return [];
  210. },
  211. _getTotal: function (files) {
  212. var total = 0;
  213. $.each(files, function (index, file) {
  214. total += file.size || 1;
  215. });
  216. return total;
  217. },
  218. _onProgress: function (e, data) {
  219. if (e.lengthComputable) {
  220. var now = +(new Date()),
  221. total,
  222. loaded;
  223. if (data._time && data.progressInterval &&
  224. (now - data._time < data.progressInterval) &&
  225. e.loaded !== e.total) {
  226. return;
  227. }
  228. data._time = now;
  229. total = data.total || this._getTotal(data.files);
  230. loaded = parseInt(
  231. e.loaded / e.total * (data.chunkSize || total),
  232. 10
  233. ) + (data.uploadedBytes || 0);
  234. this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
  235. data.lengthComputable = true;
  236. data.loaded = loaded;
  237. data.total = total;
  238. data.bitrate = data._bitrateTimer.getBitrate(
  239. now,
  240. loaded,
  241. data.bitrateInterval
  242. );
  243. // Trigger a custom progress event with a total data property set
  244. // to the file size(s) of the current upload and a loaded data
  245. // property calculated accordingly:
  246. this._trigger('progress', e, data);
  247. // Trigger a global progress event for all current file uploads,
  248. // including ajax calls queued for sequential file uploads:
  249. this._trigger('progressall', e, {
  250. lengthComputable: true,
  251. loaded: this._loaded,
  252. total: this._total,
  253. bitrate: this._bitrateTimer.getBitrate(
  254. now,
  255. this._loaded,
  256. data.bitrateInterval
  257. )
  258. });
  259. }
  260. },
  261. _initProgressListener: function (options) {
  262. var that = this,
  263. xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
  264. // Accesss to the native XHR object is required to add event listeners
  265. // for the upload progress event:
  266. if (xhr.upload) {
  267. $(xhr.upload).bind('progress', function (e) {
  268. var oe = e.originalEvent;
  269. // Make sure the progress event properties get copied over:
  270. e.lengthComputable = oe.lengthComputable;
  271. e.loaded = oe.loaded;
  272. e.total = oe.total;
  273. that._onProgress(e, options);
  274. });
  275. options.xhr = function () {
  276. return xhr;
  277. };
  278. }
  279. },
  280. _initXHRData: function (options) {
  281. var formData,
  282. file = options.files[0],
  283. // Ignore non-multipart setting if not supported:
  284. multipart = options.multipart || !$.support.xhrFileUpload,
  285. paramName = options.paramName[0];
  286. options.headers = options.headers || {};
  287. if (options.contentRange) {
  288. options.headers['Content-Range'] = options.contentRange;
  289. }
  290. if (!multipart) {
  291. options.headers['Content-Disposition'] = 'attachment; filename="' +
  292. encodeURI(file.name) + '"';
  293. options.contentType = file.type;
  294. options.data = options.blob || file;
  295. } else if ($.support.xhrFormDataFileUpload) {
  296. if (options.postMessage) {
  297. // window.postMessage does not allow sending FormData
  298. // objects, so we just add the File/Blob objects to
  299. // the formData array and let the postMessage window
  300. // create the FormData object out of this array:
  301. formData = this._getFormData(options);
  302. if (options.blob) {
  303. formData.push({
  304. name: paramName,
  305. value: options.blob
  306. });
  307. } else {
  308. $.each(options.files, function (index, file) {
  309. formData.push({
  310. name: options.paramName[index] || paramName,
  311. value: file
  312. });
  313. });
  314. }
  315. } else {
  316. if (options.formData instanceof FormData) {
  317. formData = options.formData;
  318. } else {
  319. formData = new FormData();
  320. $.each(this._getFormData(options), function (index, field) {
  321. formData.append(field.name, field.value);
  322. });
  323. }
  324. if (options.blob) {
  325. options.headers['Content-Disposition'] = 'attachment; filename="' +
  326. encodeURI(file.name) + '"';
  327. formData.append(paramName, options.blob, file.name);
  328. } else {
  329. $.each(options.files, function (index, file) {
  330. // Files are also Blob instances, but some browsers
  331. // (Firefox 3.6) support the File API but not Blobs.
  332. // This check allows the tests to run with
  333. // dummy objects:
  334. if ((window.Blob && file instanceof Blob) ||
  335. (window.File && file instanceof File)) {
  336. formData.append(
  337. options.paramName[index] || paramName,
  338. file,
  339. file.name
  340. );
  341. }
  342. });
  343. }
  344. }
  345. options.data = formData;
  346. }
  347. // Blob reference is not needed anymore, free memory:
  348. options.blob = null;
  349. },
  350. _initIframeSettings: function (options) {
  351. // Setting the dataType to iframe enables the iframe transport:
  352. options.dataType = 'iframe ' + (options.dataType || '');
  353. // The iframe transport accepts a serialized array as form data:
  354. options.formData = this._getFormData(options);
  355. // Add redirect url to form data on cross-domain uploads:
  356. if (options.redirect && $('<a></a>').prop('href', options.url)
  357. .prop('host') !== location.host) {
  358. options.formData.push({
  359. name: options.redirectParamName || 'redirect',
  360. value: options.redirect
  361. });
  362. }
  363. },
  364. _initDataSettings: function (options) {
  365. if (this._isXHRUpload(options)) {
  366. if (!this._chunkedUpload(options, true)) {
  367. if (!options.data) {
  368. this._initXHRData(options);
  369. }
  370. this._initProgressListener(options);
  371. }
  372. if (options.postMessage) {
  373. // Setting the dataType to postmessage enables the
  374. // postMessage transport:
  375. options.dataType = 'postmessage ' + (options.dataType || '');
  376. }
  377. } else {
  378. this._initIframeSettings(options, 'iframe');
  379. }
  380. },
  381. _getParamName: function (options) {
  382. var fileInput = $(options.fileInput),
  383. paramName = options.paramName;
  384. if (!paramName) {
  385. paramName = [];
  386. fileInput.each(function () {
  387. var input = $(this),
  388. name = input.prop('name') || 'files[]',
  389. i = (input.prop('files') || [1]).length;
  390. while (i) {
  391. paramName.push(name);
  392. i -= 1;
  393. }
  394. });
  395. if (!paramName.length) {
  396. paramName = [fileInput.prop('name') || 'files[]'];
  397. }
  398. } else if (!$.isArray(paramName)) {
  399. paramName = [paramName];
  400. }
  401. return paramName;
  402. },
  403. _initFormSettings: function (options) {
  404. // Retrieve missing options from the input field and the
  405. // associated form, if available:
  406. if (!options.form || !options.form.length) {
  407. options.form = $(options.fileInput.prop('form'));
  408. // If the given file input doesn't have an associated form,
  409. // use the default widget file input's form:
  410. if (!options.form.length) {
  411. options.form = $(this.options.fileInput.prop('form'));
  412. }
  413. }
  414. options.paramName = this._getParamName(options);
  415. if (!options.url) {
  416. options.url = options.form.prop('action') || location.href;
  417. }
  418. // The HTTP request method must be "POST" or "PUT":
  419. options.type = (options.type || options.form.prop('method') || '')
  420. .toUpperCase();
  421. if (options.type !== 'POST' && options.type !== 'PUT') {
  422. options.type = 'POST';
  423. }
  424. if (!options.formAcceptCharset) {
  425. options.formAcceptCharset = options.form.attr('accept-charset');
  426. }
  427. },
  428. _getAJAXSettings: function (data) {
  429. var options = $.extend({}, this.options, data);
  430. this._initFormSettings(options);
  431. this._initDataSettings(options);
  432. return options;
  433. },
  434. // Maps jqXHR callbacks to the equivalent
  435. // methods of the given Promise object:
  436. _enhancePromise: function (promise) {
  437. promise.success = promise.done;
  438. promise.error = promise.fail;
  439. promise.complete = promise.always;
  440. return promise;
  441. },
  442. // Creates and returns a Promise object enhanced with
  443. // the jqXHR methods abort, success, error and complete:
  444. _getXHRPromise: function (resolveOrReject, context, args) {
  445. var dfd = $.Deferred(),
  446. promise = dfd.promise();
  447. context = context || this.options.context || promise;
  448. if (resolveOrReject === true) {
  449. dfd.resolveWith(context, args);
  450. } else if (resolveOrReject === false) {
  451. dfd.rejectWith(context, args);
  452. }
  453. promise.abort = dfd.promise;
  454. return this._enhancePromise(promise);
  455. },
  456. // Parses the Range header from the server response
  457. // and returns the uploaded bytes:
  458. _getUploadedBytes: function (jqXHR) {
  459. var range = jqXHR.getResponseHeader('Range'),
  460. parts = range && range.split('-'),
  461. upperBytesPos = parts && parts.length > 1 &&
  462. parseInt(parts[1], 10);
  463. return upperBytesPos && upperBytesPos + 1;
  464. },
  465. // Uploads a file in multiple, sequential requests
  466. // by splitting the file up in multiple blob chunks.
  467. // If the second parameter is true, only tests if the file
  468. // should be uploaded in chunks, but does not invoke any
  469. // upload requests:
  470. _chunkedUpload: function (options, testOnly) {
  471. var that = this,
  472. file = options.files[0],
  473. fs = file.size,
  474. ub = options.uploadedBytes = options.uploadedBytes || 0,
  475. mcs = options.maxChunkSize || fs,
  476. slice = file.slice || file.webkitSlice || file.mozSlice,
  477. dfd = $.Deferred(),
  478. promise = dfd.promise(),
  479. jqXHR,
  480. upload;
  481. if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
  482. options.data) {
  483. return false;
  484. }
  485. if (testOnly) {
  486. return true;
  487. }
  488. if (ub >= fs) {
  489. file.error = 'Uploaded bytes exceed file size';
  490. return this._getXHRPromise(
  491. false,
  492. options.context,
  493. [null, 'error', file.error]
  494. );
  495. }
  496. // The chunk upload method:
  497. upload = function (i) {
  498. // Clone the options object for each chunk upload:
  499. var o = $.extend({}, options);
  500. o.blob = slice.call(
  501. file,
  502. ub,
  503. ub + mcs,
  504. file.type
  505. );
  506. // Store the current chunk size, as the blob itself
  507. // will be dereferenced after data processing:
  508. o.chunkSize = o.blob.size;
  509. // Expose the chunk bytes position range:
  510. o.contentRange = 'bytes ' + ub + '-' +
  511. (ub + o.chunkSize - 1) + '/' + fs;
  512. // Process the upload data (the blob and potential form data):
  513. that._initXHRData(o);
  514. // Add progress listeners for this chunk upload:
  515. that._initProgressListener(o);
  516. jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
  517. .done(function (result, textStatus, jqXHR) {
  518. ub = that._getUploadedBytes(jqXHR) ||
  519. (ub + o.chunkSize);
  520. // Create a progress event if upload is done and
  521. // no progress event has been invoked for this chunk:
  522. if (!o.loaded) {
  523. that._onProgress($.Event('progress', {
  524. lengthComputable: true,
  525. loaded: ub - o.uploadedBytes,
  526. total: ub - o.uploadedBytes
  527. }), o);
  528. }
  529. options.uploadedBytes = o.uploadedBytes = ub;
  530. if (ub < fs) {
  531. // File upload not yet complete,
  532. // continue with the next chunk:
  533. upload();
  534. } else {
  535. dfd.resolveWith(
  536. o.context,
  537. [result, textStatus, jqXHR]
  538. );
  539. }
  540. })
  541. .fail(function (jqXHR, textStatus, errorThrown) {
  542. dfd.rejectWith(
  543. o.context,
  544. [jqXHR, textStatus, errorThrown]
  545. );
  546. });
  547. };
  548. this._enhancePromise(promise);
  549. promise.abort = function () {
  550. return jqXHR.abort();
  551. };
  552. upload();
  553. return promise;
  554. },
  555. _beforeSend: function (e, data) {
  556. if (this._active === 0) {
  557. // the start callback is triggered when an upload starts
  558. // and no other uploads are currently running,
  559. // equivalent to the global ajaxStart event:
  560. this._trigger('start');
  561. // Set timer for global bitrate progress calculation:
  562. this._bitrateTimer = new this._BitrateTimer();
  563. }
  564. this._active += 1;
  565. // Initialize the global progress values:
  566. this._loaded += data.uploadedBytes || 0;
  567. this._total += this._getTotal(data.files);
  568. },
  569. _onDone: function (result, textStatus, jqXHR, options) {
  570. if (!this._isXHRUpload(options)) {
  571. // Create a progress event for each iframe load:
  572. this._onProgress($.Event('progress', {
  573. lengthComputable: true,
  574. loaded: 1,
  575. total: 1
  576. }), options);
  577. }
  578. options.result = result;
  579. options.textStatus = textStatus;
  580. options.jqXHR = jqXHR;
  581. this._trigger('done', null, options);
  582. },
  583. _onFail: function (jqXHR, textStatus, errorThrown, options) {
  584. options.jqXHR = jqXHR;
  585. options.textStatus = textStatus;
  586. options.errorThrown = errorThrown;
  587. this._trigger('fail', null, options);
  588. if (options.recalculateProgress) {
  589. // Remove the failed (error or abort) file upload from
  590. // the global progress calculation:
  591. this._loaded -= options.loaded || options.uploadedBytes || 0;
  592. this._total -= options.total || this._getTotal(options.files);
  593. }
  594. },
  595. _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
  596. this._active -= 1;
  597. options.textStatus = textStatus;
  598. if (jqXHRorError && jqXHRorError.always) {
  599. options.jqXHR = jqXHRorError;
  600. options.result = jqXHRorResult;
  601. } else {
  602. options.jqXHR = jqXHRorResult;
  603. options.errorThrown = jqXHRorError;
  604. }
  605. this._trigger('always', null, options);
  606. if (this._active === 0) {
  607. // The stop callback is triggered when all uploads have
  608. // been completed, equivalent to the global ajaxStop event:
  609. this._trigger('stop');
  610. // Reset the global progress values:
  611. this._loaded = this._total = 0;
  612. this._bitrateTimer = null;
  613. }
  614. },
  615. _onSend: function (e, data) {
  616. var that = this,
  617. jqXHR,
  618. aborted,
  619. slot,
  620. pipe,
  621. options = that._getAJAXSettings(data),
  622. send = function () {
  623. that._sending += 1;
  624. // Set timer for bitrate progress calculation:
  625. options._bitrateTimer = new that._BitrateTimer();
  626. jqXHR = jqXHR || (
  627. ((aborted || that._trigger('send', e, options) === false) &&
  628. that._getXHRPromise(false, options.context, aborted)) ||
  629. that._chunkedUpload(options) || $.ajax(options)
  630. ).done(function (result, textStatus, jqXHR) {
  631. that._onDone(result, textStatus, jqXHR, options);
  632. }).fail(function (jqXHR, textStatus, errorThrown) {
  633. that._onFail(jqXHR, textStatus, errorThrown, options);
  634. }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
  635. that._sending -= 1;
  636. that._onAlways(
  637. jqXHRorResult,
  638. textStatus,
  639. jqXHRorError,
  640. options
  641. );
  642. if (options.limitConcurrentUploads &&
  643. options.limitConcurrentUploads > that._sending) {
  644. // Start the next queued upload,
  645. // that has not been aborted:
  646. var nextSlot = that._slots.shift(),
  647. isPending;
  648. while (nextSlot) {
  649. // jQuery 1.6 doesn't provide .state(),
  650. // while jQuery 1.8+ removed .isRejected():
  651. isPending = nextSlot.state ?
  652. nextSlot.state() === 'pending' :
  653. !nextSlot.isRejected();
  654. if (isPending) {
  655. nextSlot.resolve();
  656. break;
  657. }
  658. nextSlot = that._slots.shift();
  659. }
  660. }
  661. });
  662. return jqXHR;
  663. };
  664. this._beforeSend(e, options);
  665. if (this.options.sequentialUploads ||
  666. (this.options.limitConcurrentUploads &&
  667. this.options.limitConcurrentUploads <= this._sending)) {
  668. if (this.options.limitConcurrentUploads > 1) {
  669. slot = $.Deferred();
  670. this._slots.push(slot);
  671. pipe = slot.pipe(send);
  672. } else {
  673. pipe = (this._sequence = this._sequence.pipe(send, send));
  674. }
  675. // Return the piped Promise object, enhanced with an abort method,
  676. // which is delegated to the jqXHR object of the current upload,
  677. // and jqXHR callbacks mapped to the equivalent Promise methods:
  678. pipe.abort = function () {
  679. aborted = [undefined, 'abort', 'abort'];
  680. if (!jqXHR) {
  681. if (slot) {
  682. slot.rejectWith(options.context, aborted);
  683. }
  684. return send();
  685. }
  686. return jqXHR.abort();
  687. };
  688. return this._enhancePromise(pipe);
  689. }
  690. return send();
  691. },
  692. _onAdd: function (e, data) {
  693. var that = this,
  694. result = true,
  695. options = $.extend({}, this.options, data),
  696. limit = options.limitMultiFileUploads,
  697. paramName = this._getParamName(options),
  698. paramNameSet,
  699. paramNameSlice,
  700. fileSet,
  701. i;
  702. if (!(options.singleFileUploads || limit) ||
  703. !this._isXHRUpload(options)) {
  704. fileSet = [data.files];
  705. paramNameSet = [paramName];
  706. } else if (!options.singleFileUploads && limit) {
  707. fileSet = [];
  708. paramNameSet = [];
  709. for (i = 0; i < data.files.length; i += limit) {
  710. fileSet.push(data.files.slice(i, i + limit));
  711. paramNameSlice = paramName.slice(i, i + limit);
  712. if (!paramNameSlice.length) {
  713. paramNameSlice = paramName;
  714. }
  715. paramNameSet.push(paramNameSlice);
  716. }
  717. } else {
  718. paramNameSet = paramName;
  719. }
  720. data.originalFiles = data.files;
  721. $.each(fileSet || data.files, function (index, element) {
  722. var newData = $.extend({}, data);
  723. newData.files = fileSet ? element : [element];
  724. newData.paramName = paramNameSet[index];
  725. newData.submit = function () {
  726. newData.jqXHR = this.jqXHR =
  727. (that._trigger('submit', e, this) !== false) &&
  728. that._onSend(e, this);
  729. return this.jqXHR;
  730. };
  731. result = that._trigger('add', e, newData);
  732. return result;
  733. });
  734. return result;
  735. },
  736. _replaceFileInput: function (input) {
  737. var inputClone = input.clone(true);
  738. $('<form></form>').append(inputClone)[0].reset();
  739. // Detaching allows to insert the fileInput on another form
  740. // without loosing the file input value:
  741. input.after(inputClone).detach();
  742. // Avoid memory leaks with the detached file input:
  743. $.cleanData(input.unbind('remove'));
  744. // Replace the original file input element in the fileInput
  745. // elements set with the clone, which has been copied including
  746. // event handlers:
  747. this.options.fileInput = this.options.fileInput.map(function (i, el) {
  748. if (el === input[0]) {
  749. return inputClone[0];
  750. }
  751. return el;
  752. });
  753. // If the widget has been initialized on the file input itself,
  754. // override this.element with the file input clone:
  755. if (input[0] === this.element[0]) {
  756. this.element = inputClone;
  757. }
  758. },
  759. _handleFileTreeEntry: function (entry, path) {
  760. var that = this,
  761. dfd = $.Deferred(),
  762. errorHandler = function (e) {
  763. if (e && !e.entry) {
  764. e.entry = entry;
  765. }
  766. // Since $.when returns immediately if one
  767. // Deferred is rejected, we use resolve instead.
  768. // This allows valid files and invalid items
  769. // to be returned together in one set:
  770. dfd.resolve([e]);
  771. },
  772. dirReader;
  773. path = path || '';
  774. if (entry.isFile) {
  775. if (entry._file) {
  776. // Workaround for Chrome bug #149735
  777. entry._file.relativePath = path;
  778. dfd.resolve(entry._file);
  779. } else {
  780. entry.file(function (file) {
  781. file.relativePath = path;
  782. dfd.resolve(file);
  783. }, errorHandler);
  784. }
  785. } else if (entry.isDirectory) {
  786. dirReader = entry.createReader();
  787. dirReader.readEntries(function (entries) {
  788. that._handleFileTreeEntries(
  789. entries,
  790. path + entry.name + '/'
  791. ).done(function (files) {
  792. dfd.resolve(files);
  793. }).fail(errorHandler);
  794. }, errorHandler);
  795. } else {
  796. // Return an empy list for file system items
  797. // other than files or directories:
  798. dfd.resolve([]);
  799. }
  800. return dfd.promise();
  801. },
  802. _handleFileTreeEntries: function (entries, path) {
  803. var that = this;
  804. return $.when.apply(
  805. $,
  806. $.map(entries, function (entry) {
  807. return that._handleFileTreeEntry(entry, path);
  808. })
  809. ).pipe(function () {
  810. return Array.prototype.concat.apply(
  811. [],
  812. arguments
  813. );
  814. });
  815. },
  816. _getDroppedFiles: function (dataTransfer) {
  817. dataTransfer = dataTransfer || {};
  818. var items = dataTransfer.items;
  819. if (items && items.length && (items[0].webkitGetAsEntry ||
  820. items[0].getAsEntry)) {
  821. return this._handleFileTreeEntries(
  822. $.map(items, function (item) {
  823. var entry;
  824. if (item.webkitGetAsEntry) {
  825. entry = item.webkitGetAsEntry();
  826. if (entry) {
  827. // Workaround for Chrome bug #149735:
  828. entry._file = item.getAsFile();
  829. }
  830. return entry;
  831. }
  832. return item.getAsEntry();
  833. })
  834. );
  835. }
  836. return $.Deferred().resolve(
  837. $.makeArray(dataTransfer.files)
  838. ).promise();
  839. },
  840. _getSingleFileInputFiles: function (fileInput) {
  841. fileInput = $(fileInput);
  842. var entries = fileInput.prop('webkitEntries') ||
  843. fileInput.prop('entries'),
  844. files,
  845. value;
  846. if (entries && entries.length) {
  847. return this._handleFileTreeEntries(entries);
  848. }
  849. files = $.makeArray(fileInput.prop('files'));
  850. if (!files.length) {
  851. value = fileInput.prop('value');
  852. if (!value) {
  853. return $.Deferred().resolve([]).promise();
  854. }
  855. // If the files property is not available, the browser does not
  856. // support the File API and we add a pseudo File object with
  857. // the input value as name with path information removed:
  858. files = [{name: value.replace(/^.*\\/, '')}];
  859. } else if (files[0].name === undefined && files[0].fileName) {
  860. // File normalization for Safari 4 and Firefox 3:
  861. $.each(files, function (index, file) {
  862. file.name = file.fileName;
  863. file.size = file.fileSize;
  864. });
  865. }
  866. return $.Deferred().resolve(files).promise();
  867. },
  868. _getFileInputFiles: function (fileInput) {
  869. if (!(fileInput instanceof $) || fileInput.length === 1) {
  870. return this._getSingleFileInputFiles(fileInput);
  871. }
  872. return $.when.apply(
  873. $,
  874. $.map(fileInput, this._getSingleFileInputFiles)
  875. ).pipe(function () {
  876. return Array.prototype.concat.apply(
  877. [],
  878. arguments
  879. );
  880. });
  881. },
  882. _onChange: function (e) {
  883. var that = this,
  884. data = {
  885. fileInput: $(e.target),
  886. form: $(e.target.form)
  887. };
  888. this._getFileInputFiles(data.fileInput).always(function (files) {
  889. data.files = files;
  890. if (that.options.replaceFileInput) {
  891. that._replaceFileInput(data.fileInput);
  892. }
  893. if (that._trigger('change', e, data) !== false) {
  894. that._onAdd(e, data);
  895. }
  896. });
  897. },
  898. _onPaste: function (e) {
  899. var cbd = e.originalEvent.clipboardData,
  900. items = (cbd && cbd.items) || [],
  901. data = {files: []};
  902. $.each(items, function (index, item) {
  903. var file = item.getAsFile && item.getAsFile();
  904. if (file) {
  905. data.files.push(file);
  906. }
  907. });
  908. if (this._trigger('paste', e, data) === false ||
  909. this._onAdd(e, data) === false) {
  910. return false;
  911. }
  912. },
  913. _onDrop: function (e) {
  914. var that = this,
  915. dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
  916. data = {};
  917. if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
  918. e.preventDefault();
  919. }
  920. this._getDroppedFiles(dataTransfer).always(function (files) {
  921. data.files = files;
  922. if (that._trigger('drop', e, data) !== false) {
  923. that._onAdd(e, data);
  924. }
  925. });
  926. },
  927. _onDragOver: function (e) {
  928. var dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
  929. if (this._trigger('dragover', e) === false) {
  930. return false;
  931. }
  932. if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1) {
  933. dataTransfer.dropEffect = 'copy';
  934. e.preventDefault();
  935. }
  936. },
  937. _initEventHandlers: function () {
  938. if (this._isXHRUpload(this.options)) {
  939. this._on(this.options.dropZone, {
  940. dragover: this._onDragOver,
  941. drop: this._onDrop
  942. });
  943. this._on(this.options.pasteZone, {
  944. paste: this._onPaste
  945. });
  946. }
  947. this._on(this.options.fileInput, {
  948. change: this._onChange
  949. });
  950. },
  951. _destroyEventHandlers: function () {
  952. this._off(this.options.dropZone, 'dragover drop');
  953. this._off(this.options.pasteZone, 'paste');
  954. this._off(this.options.fileInput, 'change');
  955. },
  956. _setOption: function (key, value) {
  957. var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
  958. if (refresh) {
  959. this._destroyEventHandlers();
  960. }
  961. this._super(key, value);
  962. if (refresh) {
  963. this._initSpecialOptions();
  964. this._initEventHandlers();
  965. }
  966. },
  967. _initSpecialOptions: function () {
  968. var options = this.options;
  969. if (options.fileInput === undefined) {
  970. options.fileInput = this.element.is('input[type="file"]') ?
  971. this.element : this.element.find('input[type="file"]');
  972. } else if (!(options.fileInput instanceof $)) {
  973. options.fileInput = $(options.fileInput);
  974. }
  975. if (!(options.dropZone instanceof $)) {
  976. options.dropZone = $(options.dropZone);
  977. }
  978. if (!(options.pasteZone instanceof $)) {
  979. options.pasteZone = $(options.pasteZone);
  980. }
  981. },
  982. _create: function () {
  983. var options = this.options;
  984. // Initialize options set via HTML5 data-attributes:
  985. $.extend(options, $(this.element[0].cloneNode(false)).data());
  986. this._initSpecialOptions();
  987. this._slots = [];
  988. this._sequence = this._getXHRPromise(true);
  989. this._sending = this._active = this._loaded = this._total = 0;
  990. this._initEventHandlers();
  991. },
  992. _destroy: function () {
  993. this._destroyEventHandlers();
  994. },
  995. // This method is exposed to the widget API and allows adding files
  996. // using the fileupload API. The data parameter accepts an object which
  997. // must have a files property and can contain additional options:
  998. // .fileupload('add', {files: filesList});
  999. add: function (data) {
  1000. var that = this;
  1001. if (!data || this.options.disabled) {
  1002. return;
  1003. }
  1004. if (data.fileInput && !data.files) {
  1005. this._getFileInputFiles(data.fileInput).always(function (files) {
  1006. data.files = files;
  1007. that._onAdd(null, data);
  1008. });
  1009. } else {
  1010. data.files = $.makeArray(data.files);
  1011. this._onAdd(null, data);
  1012. }
  1013. },
  1014. // This method is exposed to the widget API and allows sending files
  1015. // using the fileupload API. The data parameter accepts an object which
  1016. // must have a files or fileInput property and can contain additional options:
  1017. // .fileupload('send', {files: filesList});
  1018. // The method returns a Promise object for the file upload call.
  1019. send: function (data) {
  1020. if (data && !this.options.disabled) {
  1021. if (data.fileInput && !data.files) {
  1022. var that = this,
  1023. dfd = $.Deferred(),
  1024. promise = dfd.promise(),
  1025. jqXHR,
  1026. aborted;
  1027. promise.abort = function () {
  1028. aborted = true;
  1029. if (jqXHR) {
  1030. return jqXHR.abort();
  1031. }
  1032. dfd.reject(null, 'abort', 'abort');
  1033. return promise;
  1034. };
  1035. this._getFileInputFiles(data.fileInput).always(
  1036. function (files) {
  1037. if (aborted) {
  1038. return;
  1039. }
  1040. data.files = files;
  1041. jqXHR = that._onSend(null, data).then(
  1042. function (result, textStatus, jqXHR) {
  1043. dfd.resolve(result, textStatus, jqXHR);
  1044. },
  1045. function (jqXHR, textStatus, errorThrown) {
  1046. dfd.reject(jqXHR, textStatus, errorThrown);
  1047. }
  1048. );
  1049. }
  1050. );
  1051. return this._enhancePromise(promise);
  1052. }
  1053. data.files = $.makeArray(data.files);
  1054. if (data.files.length) {
  1055. return this._onSend(null, data);
  1056. }
  1057. }
  1058. return this._getXHRPromise(false, data && data.context);
  1059. }
  1060. });
  1061. }));