jquery-file-upload-rails 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (84) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +20 -0
  3. data/README.md +55 -0
  4. data/Rakefile +32 -0
  5. data/app/views/jquery_file_upload/basic_plus_ui/_download.html.erb +43 -0
  6. data/app/views/jquery_file_upload/basic_plus_ui/_form.html.haml +35 -0
  7. data/app/views/jquery_file_upload/basic_plus_ui/_upload.html.erb +32 -0
  8. data/config/locales/jquery_file_upload.cs.yml +16 -0
  9. data/config/locales/jquery_file_upload.en.yml +16 -0
  10. data/lib/jquery-file-upload-rails.rb +1 -0
  11. data/lib/jquery_file_upload/rails.rb +6 -0
  12. data/lib/jquery_file_upload/rails/version.rb +5 -0
  13. data/test/dummy/README.rdoc +28 -0
  14. data/test/dummy/app/assets/javascripts/application.js +13 -0
  15. data/test/dummy/app/assets/stylesheets/application.css +13 -0
  16. data/test/dummy/app/controllers/application_controller.rb +5 -0
  17. data/test/dummy/app/helpers/application_helper.rb +2 -0
  18. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  19. data/test/dummy/bin/bundle +3 -0
  20. data/test/dummy/bin/rails +4 -0
  21. data/test/dummy/bin/rake +4 -0
  22. data/test/dummy/config.ru +4 -0
  23. data/test/dummy/config/application.rb +22 -0
  24. data/test/dummy/config/boot.rb +5 -0
  25. data/test/dummy/config/database.yml +25 -0
  26. data/test/dummy/config/environment.rb +5 -0
  27. data/test/dummy/config/environments/development.rb +29 -0
  28. data/test/dummy/config/environments/production.rb +80 -0
  29. data/test/dummy/config/environments/test.rb +36 -0
  30. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  31. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  32. data/test/dummy/config/initializers/inflections.rb +16 -0
  33. data/test/dummy/config/initializers/mime_types.rb +5 -0
  34. data/test/dummy/config/initializers/secret_token.rb +12 -0
  35. data/test/dummy/config/initializers/session_store.rb +3 -0
  36. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  37. data/test/dummy/config/locales/en.yml +23 -0
  38. data/test/dummy/config/routes.rb +56 -0
  39. data/test/dummy/db/test.sqlite3 +0 -0
  40. data/test/jquery_file_upload_rails_test.rb +7 -0
  41. data/test/test_helper.rb +15 -0
  42. data/vendor/assets/images/jquery-file-upload/loading.gif +0 -0
  43. data/vendor/assets/images/jquery-file-upload/progressbar.gif +0 -0
  44. data/vendor/assets/javascripts/jquery-file-upload/app.js +101 -0
  45. data/vendor/assets/javascripts/jquery-file-upload/basic-plus-ui-no-widget.js.coffee +35 -0
  46. data/vendor/assets/javascripts/jquery-file-upload/basic-plus-ui.js.coffee +38 -0
  47. data/vendor/assets/javascripts/jquery-file-upload/cors/jquery.postmessage-transport.js +118 -0
  48. data/vendor/assets/javascripts/jquery-file-upload/cors/jquery.xdr-transport.js +87 -0
  49. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-angular.js +428 -0
  50. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-audio.js +106 -0
  51. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-image.js +295 -0
  52. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-jquery-ui.js +144 -0
  53. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-process.js +172 -0
  54. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-ui.js +699 -0
  55. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-validate.js +120 -0
  56. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload-video.js +106 -0
  57. data/vendor/assets/javascripts/jquery-file-upload/jquery.fileupload.js +1416 -0
  58. data/vendor/assets/javascripts/jquery-file-upload/jquery.iframe-transport.js +210 -0
  59. data/vendor/assets/javascripts/jquery-file-upload/main.js.coffee +4 -0
  60. data/vendor/assets/javascripts/jquery-file-upload/vendor/canvas-to-blob/canvas-to-blob.js +95 -0
  61. data/vendor/assets/javascripts/jquery-file-upload/vendor/canvas-to-blob/canvas-to-blob.min.js +1 -0
  62. data/vendor/assets/javascripts/jquery-file-upload/vendor/jquery.ui.widget.js +530 -0
  63. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/demo.js +138 -0
  64. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/load-image-exif-map.js +384 -0
  65. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/load-image-exif.js +299 -0
  66. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/load-image-ios.js +181 -0
  67. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/load-image-meta.js +137 -0
  68. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/load-image-orientation.js +159 -0
  69. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/load-image.js +276 -0
  70. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/load-image.min.js +1 -0
  71. data/vendor/assets/javascripts/jquery-file-upload/vendor/load-image/vendor/jquery.Jcrop.js +1694 -0
  72. data/vendor/assets/javascripts/jquery-file-upload/vendor/templates/compile.js +84 -0
  73. data/vendor/assets/javascripts/jquery-file-upload/vendor/templates/demo.js +48 -0
  74. data/vendor/assets/javascripts/jquery-file-upload/vendor/templates/runtime.js +47 -0
  75. data/vendor/assets/javascripts/jquery-file-upload/vendor/templates/tmpl.js +87 -0
  76. data/vendor/assets/javascripts/jquery-file-upload/vendor/templates/tmpl.min.js +1 -0
  77. data/vendor/assets/stylesheets/jquery-file-upload/demo-ie8.css +21 -0
  78. data/vendor/assets/stylesheets/jquery-file-upload/demo.css +67 -0
  79. data/vendor/assets/stylesheets/jquery-file-upload/jquery.fileupload-noscript.css +22 -0
  80. data/vendor/assets/stylesheets/jquery-file-upload/jquery.fileupload-ui-noscript.css +17 -0
  81. data/vendor/assets/stylesheets/jquery-file-upload/jquery.fileupload-ui.css.scss +57 -0
  82. data/vendor/assets/stylesheets/jquery-file-upload/jquery.fileupload.css +36 -0
  83. data/vendor/assets/stylesheets/jquery-file-upload/style.css +15 -0
  84. metadata +196 -0
@@ -0,0 +1,120 @@
1
+ /*
2
+ * jQuery File Upload Validation Plugin 1.1.2
3
+ * https://github.com/blueimp/jQuery-File-Upload
4
+ *
5
+ * Copyright 2013, Sebastian Tschan
6
+ * https://blueimp.net
7
+ *
8
+ * Licensed under the MIT license:
9
+ * http://www.opensource.org/licenses/MIT
10
+ */
11
+
12
+ /*jslint nomen: true, unparam: true, regexp: true */
13
+ /*global define, window */
14
+
15
+ (function (factory) {
16
+ 'use strict';
17
+ if (typeof define === 'function' && define.amd) {
18
+ // Register as an anonymous AMD module:
19
+ define([
20
+ 'jquery',
21
+ './jquery.fileupload-process'
22
+ ], factory);
23
+ } else {
24
+ // Browser globals:
25
+ factory(
26
+ window.jQuery
27
+ );
28
+ }
29
+ }(function ($) {
30
+ 'use strict';
31
+
32
+ // Append to the default processQueue:
33
+ $.blueimp.fileupload.prototype.options.processQueue.push(
34
+ {
35
+ action: 'validate',
36
+ // Always trigger this action,
37
+ // even if the previous action was rejected:
38
+ always: true,
39
+ // Options taken from the global options map:
40
+ acceptFileTypes: '@',
41
+ maxFileSize: '@',
42
+ minFileSize: '@',
43
+ maxNumberOfFiles: '@',
44
+ disabled: '@disableValidation'
45
+ }
46
+ );
47
+
48
+ // The File Upload Validation plugin extends the fileupload widget
49
+ // with file validation functionality:
50
+ $.widget('blueimp.fileupload', $.blueimp.fileupload, {
51
+
52
+ options: {
53
+ /*
54
+ // The regular expression for allowed file types, matches
55
+ // against either file type or file name:
56
+ acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
57
+ // The maximum allowed file size in bytes:
58
+ maxFileSize: 10000000, // 10 MB
59
+ // The minimum allowed file size in bytes:
60
+ minFileSize: undefined, // No minimal file size
61
+ // The limit of files to be uploaded:
62
+ maxNumberOfFiles: 10,
63
+ */
64
+
65
+ // Function returning the current number of files,
66
+ // has to be overriden for maxNumberOfFiles validation:
67
+ getNumberOfFiles: $.noop,
68
+
69
+ // Error and info messages:
70
+ messages: {
71
+ maxNumberOfFiles: 'Maximum number of files exceeded',
72
+ acceptFileTypes: 'File type not allowed',
73
+ maxFileSize: 'File is too large',
74
+ minFileSize: 'File is too small'
75
+ }
76
+ },
77
+
78
+ processActions: {
79
+
80
+ validate: function (data, options) {
81
+ if (options.disabled) {
82
+ return data;
83
+ }
84
+ var dfd = $.Deferred(),
85
+ settings = this.options,
86
+ file = data.files[data.index],
87
+ fileSize;
88
+ if (options.minFileSize || options.maxFileSize) {
89
+ fileSize = file.size;
90
+ }
91
+ if ($.type(options.maxNumberOfFiles) === 'number' &&
92
+ (settings.getNumberOfFiles() || 0) + data.files.length >
93
+ options.maxNumberOfFiles) {
94
+ file.error = settings.i18n('maxNumberOfFiles');
95
+ } else if (options.acceptFileTypes &&
96
+ !(options.acceptFileTypes.test(file.type) ||
97
+ options.acceptFileTypes.test(file.name))) {
98
+ file.error = settings.i18n('acceptFileTypes');
99
+ } else if (fileSize > options.maxFileSize) {
100
+ file.error = settings.i18n('maxFileSize');
101
+ } else if ($.type(fileSize) === 'number' &&
102
+ fileSize < options.minFileSize) {
103
+ file.error = settings.i18n('minFileSize');
104
+ } else {
105
+ delete file.error;
106
+ }
107
+ if (file.error || data.files.error) {
108
+ data.files.error = true;
109
+ dfd.rejectWith(this, [data]);
110
+ } else {
111
+ dfd.resolveWith(this, [data]);
112
+ }
113
+ return dfd.promise();
114
+ }
115
+
116
+ }
117
+
118
+ });
119
+
120
+ }));
@@ -0,0 +1,106 @@
1
+ /*
2
+ * jQuery File Upload Video Preview Plugin 1.0.3
3
+ * https://github.com/blueimp/jQuery-File-Upload
4
+ *
5
+ * Copyright 2013, Sebastian Tschan
6
+ * https://blueimp.net
7
+ *
8
+ * Licensed under the MIT license:
9
+ * http://www.opensource.org/licenses/MIT
10
+ */
11
+
12
+ /*jslint nomen: true, unparam: true, regexp: true */
13
+ /*global define, window, document */
14
+
15
+ (function (factory) {
16
+ 'use strict';
17
+ if (typeof define === 'function' && define.amd) {
18
+ // Register as an anonymous AMD module:
19
+ define([
20
+ 'jquery',
21
+ 'load-image',
22
+ './jquery.fileupload-process'
23
+ ], factory);
24
+ } else {
25
+ // Browser globals:
26
+ factory(
27
+ window.jQuery,
28
+ window.loadImage
29
+ );
30
+ }
31
+ }(function ($, loadImage) {
32
+ 'use strict';
33
+
34
+ // Prepend to the default processQueue:
35
+ $.blueimp.fileupload.prototype.options.processQueue.unshift(
36
+ {
37
+ action: 'loadVideo',
38
+ // Use the action as prefix for the "@" options:
39
+ prefix: true,
40
+ fileTypes: '@',
41
+ maxFileSize: '@',
42
+ disabled: '@disableVideoPreview'
43
+ },
44
+ {
45
+ action: 'setVideo',
46
+ name: '@videoPreviewName',
47
+ disabled: '@disableVideoPreview'
48
+ }
49
+ );
50
+
51
+ // The File Upload Video Preview plugin extends the fileupload widget
52
+ // with video preview functionality:
53
+ $.widget('blueimp.fileupload', $.blueimp.fileupload, {
54
+
55
+ options: {
56
+ // The regular expression for the types of video files to load,
57
+ // matched against the file type:
58
+ loadVideoFileTypes: /^video\/.*$/
59
+ },
60
+
61
+ _videoElement: document.createElement('video'),
62
+
63
+ processActions: {
64
+
65
+ // Loads the video file given via data.files and data.index
66
+ // as video element if the browser supports playing it.
67
+ // Accepts the options fileTypes (regular expression)
68
+ // and maxFileSize (integer) to limit the files to load:
69
+ loadVideo: function (data, options) {
70
+ if (options.disabled) {
71
+ return data;
72
+ }
73
+ var file = data.files[data.index],
74
+ url,
75
+ video;
76
+ if (this._videoElement.canPlayType &&
77
+ this._videoElement.canPlayType(file.type) &&
78
+ ($.type(options.maxFileSize) !== 'number' ||
79
+ file.size <= options.maxFileSize) &&
80
+ (!options.fileTypes ||
81
+ options.fileTypes.test(file.type))) {
82
+ url = loadImage.createObjectURL(file);
83
+ if (url) {
84
+ video = this._videoElement.cloneNode(false);
85
+ video.src = url;
86
+ video.controls = true;
87
+ data.video = video;
88
+ return data;
89
+ }
90
+ }
91
+ return data;
92
+ },
93
+
94
+ // Sets the video element as a property of the file object:
95
+ setVideo: function (data, options) {
96
+ if (data.video && !options.disabled) {
97
+ data.files[data.index][options.name || 'preview'] = data.video;
98
+ }
99
+ return data;
100
+ }
101
+
102
+ }
103
+
104
+ });
105
+
106
+ }));
@@ -0,0 +1,1416 @@
1
+ /*
2
+ * jQuery File Upload Plugin 5.38.0
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
+
12
+ /*jslint nomen: true, unparam: true, regexp: true */
13
+ /*global define, window, document, location, File, Blob, FormData */
14
+
15
+ (function (factory) {
16
+ 'use strict';
17
+ if (typeof define === 'function' && define.amd) {
18
+ // Register as an anonymous AMD module:
19
+ define([
20
+ 'jquery',
21
+ 'jquery.ui.widget'
22
+ ], factory);
23
+ } else {
24
+ // Browser globals:
25
+ factory(window.jQuery);
26
+ }
27
+ }(function ($) {
28
+ 'use strict';
29
+
30
+ // Detect file input support, based on
31
+ // http://viljamis.com/blog/2012/file-upload-support-on-mobile/
32
+ $.support.fileInput = !(new RegExp(
33
+ // Handle devices which give false positives for the feature detection:
34
+ '(Android (1\\.[0156]|2\\.[01]))' +
35
+ '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' +
36
+ '|(w(eb)?OSBrowser)|(webOS)' +
37
+ '|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
38
+ ).test(window.navigator.userAgent) ||
39
+ // Feature detection for all other devices:
40
+ $('<input type="file">').prop('disabled'));
41
+
42
+ // The FileReader API is not actually used, but works as feature detection,
43
+ // as some Safari versions (5?) support XHR file uploads via the FormData API,
44
+ // but not non-multipart XHR file uploads.
45
+ // window.XMLHttpRequestUpload is not available on IE10, so we check for
46
+ // window.ProgressEvent instead to detect XHR2 file upload capability:
47
+ $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader);
48
+ $.support.xhrFormDataFileUpload = !!window.FormData;
49
+
50
+ // Detect support for Blob slicing (required for chunked uploads):
51
+ $.support.blobSlice = window.Blob && (Blob.prototype.slice ||
52
+ Blob.prototype.webkitSlice || Blob.prototype.mozSlice);
53
+
54
+ // The fileupload widget listens for change events on file input fields defined
55
+ // via fileInput setting and paste or drop events of the given dropZone.
56
+ // In addition to the default jQuery Widget methods, the fileupload widget
57
+ // exposes the "add" and "send" methods, to add or directly send files using
58
+ // the fileupload API.
59
+ // By default, files added via file input selection, paste, drag & drop or
60
+ // "add" method are uploaded immediately, but it is possible to override
61
+ // the "add" callback option to queue file uploads.
62
+ $.widget('blueimp.fileupload', {
63
+
64
+ options: {
65
+ // The drop target element(s), by the default the complete document.
66
+ // Set to null to disable drag & drop support:
67
+ dropZone: $(document),
68
+ // The paste target element(s), by the default the complete document.
69
+ // Set to null to disable paste support:
70
+ pasteZone: $(document),
71
+ // The file input field(s), that are listened to for change events.
72
+ // If undefined, it is set to the file input fields inside
73
+ // of the widget element on plugin initialization.
74
+ // Set to null to disable the change listener.
75
+ fileInput: undefined,
76
+ // By default, the file input field is replaced with a clone after
77
+ // each input field change event. This is required for iframe transport
78
+ // queues and allows change events to be fired for the same file
79
+ // selection, but can be disabled by setting the following option to false:
80
+ replaceFileInput: true,
81
+ // The parameter name for the file form data (the request argument name).
82
+ // If undefined or empty, the name property of the file input field is
83
+ // used, or "files[]" if the file input name property is also empty,
84
+ // can be a string or an array of strings:
85
+ paramName: undefined,
86
+ // By default, each file of a selection is uploaded using an individual
87
+ // request for XHR type uploads. Set to false to upload file
88
+ // selections in one request each:
89
+ singleFileUploads: true,
90
+ // To limit the number of files uploaded with one XHR request,
91
+ // set the following option to an integer greater than 0:
92
+ limitMultiFileUploads: undefined,
93
+ // The following option limits the number of files uploaded with one
94
+ // XHR request to keep the request size under or equal to the defined
95
+ // limit in bytes:
96
+ limitMultiFileUploadSize: undefined,
97
+ // Multipart file uploads add a number of bytes to each uploaded file,
98
+ // therefore the following option adds an overhead for each file used
99
+ // in the limitMultiFileUploadSize configuration:
100
+ limitMultiFileUploadSizeOverhead: 512,
101
+ // Set the following option to true to issue all file upload requests
102
+ // in a sequential order:
103
+ sequentialUploads: false,
104
+ // To limit the number of concurrent uploads,
105
+ // set the following option to an integer greater than 0:
106
+ limitConcurrentUploads: undefined,
107
+ // Set the following option to true to force iframe transport uploads:
108
+ forceIframeTransport: false,
109
+ // Set the following option to the location of a redirect url on the
110
+ // origin server, for cross-domain iframe transport uploads:
111
+ redirect: undefined,
112
+ // The parameter name for the redirect url, sent as part of the form
113
+ // data and set to 'redirect' if this option is empty:
114
+ redirectParamName: undefined,
115
+ // Set the following option to the location of a postMessage window,
116
+ // to enable postMessage transport uploads:
117
+ postMessage: undefined,
118
+ // By default, XHR file uploads are sent as multipart/form-data.
119
+ // The iframe transport is always using multipart/form-data.
120
+ // Set to false to enable non-multipart XHR uploads:
121
+ multipart: true,
122
+ // To upload large files in smaller chunks, set the following option
123
+ // to a preferred maximum chunk size. If set to 0, null or undefined,
124
+ // or the browser does not support the required Blob API, files will
125
+ // be uploaded as a whole.
126
+ maxChunkSize: undefined,
127
+ // When a non-multipart upload or a chunked multipart upload has been
128
+ // aborted, this option can be used to resume the upload by setting
129
+ // it to the size of the already uploaded bytes. This option is most
130
+ // useful when modifying the options object inside of the "add" or
131
+ // "send" callbacks, as the options are cloned for each file upload.
132
+ uploadedBytes: undefined,
133
+ // By default, failed (abort or error) file uploads are removed from the
134
+ // global progress calculation. Set the following option to false to
135
+ // prevent recalculating the global progress data:
136
+ recalculateProgress: true,
137
+ // Interval in milliseconds to calculate and trigger progress events:
138
+ progressInterval: 100,
139
+ // Interval in milliseconds to calculate progress bitrate:
140
+ bitrateInterval: 500,
141
+ // By default, uploads are started automatically when adding files:
142
+ autoUpload: true,
143
+
144
+ // Error and info messages:
145
+ messages: {
146
+ uploadedBytes: 'Uploaded bytes exceed file size'
147
+ },
148
+
149
+ // Translation function, gets the message key to be translated
150
+ // and an object with context specific data as arguments:
151
+ i18n: function (message, context) {
152
+ message = this.messages[message] || message.toString();
153
+ if (context) {
154
+ $.each(context, function (key, value) {
155
+ message = message.replace('{' + key + '}', value);
156
+ });
157
+ }
158
+ return message;
159
+ },
160
+
161
+ // Additional form data to be sent along with the file uploads can be set
162
+ // using this option, which accepts an array of objects with name and
163
+ // value properties, a function returning such an array, a FormData
164
+ // object (for XHR file uploads), or a simple object.
165
+ // The form of the first fileInput is given as parameter to the function:
166
+ formData: function (form) {
167
+ return form.serializeArray();
168
+ },
169
+
170
+ // The add callback is invoked as soon as files are added to the fileupload
171
+ // widget (via file input selection, drag & drop, paste or add API call).
172
+ // If the singleFileUploads option is enabled, this callback will be
173
+ // called once for each file in the selection for XHR file uploads, else
174
+ // once for each file selection.
175
+ //
176
+ // The upload starts when the submit method is invoked on the data parameter.
177
+ // The data object contains a files property holding the added files
178
+ // and allows you to override plugin options as well as define ajax settings.
179
+ //
180
+ // Listeners for this callback can also be bound the following way:
181
+ // .bind('fileuploadadd', func);
182
+ //
183
+ // data.submit() returns a Promise object and allows to attach additional
184
+ // handlers using jQuery's Deferred callbacks:
185
+ // data.submit().done(func).fail(func).always(func);
186
+ add: function (e, data) {
187
+ if (e.isDefaultPrevented()) {
188
+ return false;
189
+ }
190
+ if (data.autoUpload || (data.autoUpload !== false &&
191
+ $(this).fileupload('option', 'autoUpload'))) {
192
+ data.process().done(function () {
193
+ data.submit();
194
+ });
195
+ }
196
+ },
197
+
198
+ // Other callbacks:
199
+
200
+ // Callback for the submit event of each file upload:
201
+ // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
202
+
203
+ // Callback for the start of each file upload request:
204
+ // send: function (e, data) {}, // .bind('fileuploadsend', func);
205
+
206
+ // Callback for successful uploads:
207
+ // done: function (e, data) {}, // .bind('fileuploaddone', func);
208
+
209
+ // Callback for failed (abort or error) uploads:
210
+ // fail: function (e, data) {}, // .bind('fileuploadfail', func);
211
+
212
+ // Callback for completed (success, abort or error) requests:
213
+ // always: function (e, data) {}, // .bind('fileuploadalways', func);
214
+
215
+ // Callback for upload progress events:
216
+ // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
217
+
218
+ // Callback for global upload progress events:
219
+ // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
220
+
221
+ // Callback for uploads start, equivalent to the global ajaxStart event:
222
+ // start: function (e) {}, // .bind('fileuploadstart', func);
223
+
224
+ // Callback for uploads stop, equivalent to the global ajaxStop event:
225
+ // stop: function (e) {}, // .bind('fileuploadstop', func);
226
+
227
+ // Callback for change events of the fileInput(s):
228
+ // change: function (e, data) {}, // .bind('fileuploadchange', func);
229
+
230
+ // Callback for paste events to the pasteZone(s):
231
+ // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
232
+
233
+ // Callback for drop events of the dropZone(s):
234
+ // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
235
+
236
+ // Callback for dragover events of the dropZone(s):
237
+ // dragover: function (e) {}, // .bind('fileuploaddragover', func);
238
+
239
+ // Callback for the start of each chunk upload request:
240
+ // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);
241
+
242
+ // Callback for successful chunk uploads:
243
+ // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);
244
+
245
+ // Callback for failed (abort or error) chunk uploads:
246
+ // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);
247
+
248
+ // Callback for completed (success, abort or error) chunk upload requests:
249
+ // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);
250
+
251
+ // The plugin options are used as settings object for the ajax calls.
252
+ // The following are jQuery ajax settings required for the file uploads:
253
+ processData: false,
254
+ contentType: false,
255
+ cache: false
256
+ },
257
+
258
+ // A list of options that require reinitializing event listeners and/or
259
+ // special initialization code:
260
+ _specialOptions: [
261
+ 'fileInput',
262
+ 'dropZone',
263
+ 'pasteZone',
264
+ 'multipart',
265
+ 'forceIframeTransport'
266
+ ],
267
+
268
+ _blobSlice: $.support.blobSlice && function () {
269
+ var slice = this.slice || this.webkitSlice || this.mozSlice;
270
+ return slice.apply(this, arguments);
271
+ },
272
+
273
+ _BitrateTimer: function () {
274
+ this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
275
+ this.loaded = 0;
276
+ this.bitrate = 0;
277
+ this.getBitrate = function (now, loaded, interval) {
278
+ var timeDiff = now - this.timestamp;
279
+ if (!this.bitrate || !interval || timeDiff > interval) {
280
+ this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
281
+ this.loaded = loaded;
282
+ this.timestamp = now;
283
+ }
284
+ return this.bitrate;
285
+ };
286
+ },
287
+
288
+ _isXHRUpload: function (options) {
289
+ return !options.forceIframeTransport &&
290
+ ((!options.multipart && $.support.xhrFileUpload) ||
291
+ $.support.xhrFormDataFileUpload);
292
+ },
293
+
294
+ _getFormData: function (options) {
295
+ var formData;
296
+ if ($.type(options.formData) === 'function') {
297
+ return options.formData(options.form);
298
+ }
299
+ if ($.isArray(options.formData)) {
300
+ return options.formData;
301
+ }
302
+ if ($.type(options.formData) === 'object') {
303
+ formData = [];
304
+ $.each(options.formData, function (name, value) {
305
+ formData.push({name: name, value: value});
306
+ });
307
+ return formData;
308
+ }
309
+ return [];
310
+ },
311
+
312
+ _getTotal: function (files) {
313
+ var total = 0;
314
+ $.each(files, function (index, file) {
315
+ total += file.size || 1;
316
+ });
317
+ return total;
318
+ },
319
+
320
+ _initProgressObject: function (obj) {
321
+ var progress = {
322
+ loaded: 0,
323
+ total: 0,
324
+ bitrate: 0
325
+ };
326
+ if (obj._progress) {
327
+ $.extend(obj._progress, progress);
328
+ } else {
329
+ obj._progress = progress;
330
+ }
331
+ },
332
+
333
+ _initResponseObject: function (obj) {
334
+ var prop;
335
+ if (obj._response) {
336
+ for (prop in obj._response) {
337
+ if (obj._response.hasOwnProperty(prop)) {
338
+ delete obj._response[prop];
339
+ }
340
+ }
341
+ } else {
342
+ obj._response = {};
343
+ }
344
+ },
345
+
346
+ _onProgress: function (e, data) {
347
+ if (e.lengthComputable) {
348
+ var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
349
+ loaded;
350
+ if (data._time && data.progressInterval &&
351
+ (now - data._time < data.progressInterval) &&
352
+ e.loaded !== e.total) {
353
+ return;
354
+ }
355
+ data._time = now;
356
+ loaded = Math.floor(
357
+ e.loaded / e.total * (data.chunkSize || data._progress.total)
358
+ ) + (data.uploadedBytes || 0);
359
+ // Add the difference from the previously loaded state
360
+ // to the global loaded counter:
361
+ this._progress.loaded += (loaded - data._progress.loaded);
362
+ this._progress.bitrate = this._bitrateTimer.getBitrate(
363
+ now,
364
+ this._progress.loaded,
365
+ data.bitrateInterval
366
+ );
367
+ data._progress.loaded = data.loaded = loaded;
368
+ data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
369
+ now,
370
+ loaded,
371
+ data.bitrateInterval
372
+ );
373
+ // Trigger a custom progress event with a total data property set
374
+ // to the file size(s) of the current upload and a loaded data
375
+ // property calculated accordingly:
376
+ this._trigger(
377
+ 'progress',
378
+ $.Event('progress', {delegatedEvent: e}),
379
+ data
380
+ );
381
+ // Trigger a global progress event for all current file uploads,
382
+ // including ajax calls queued for sequential file uploads:
383
+ this._trigger(
384
+ 'progressall',
385
+ $.Event('progressall', {delegatedEvent: e}),
386
+ this._progress
387
+ );
388
+ }
389
+ },
390
+
391
+ _initProgressListener: function (options) {
392
+ var that = this,
393
+ xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
394
+ // Accesss to the native XHR object is required to add event listeners
395
+ // for the upload progress event:
396
+ if (xhr.upload) {
397
+ $(xhr.upload).bind('progress', function (e) {
398
+ var oe = e.originalEvent;
399
+ // Make sure the progress event properties get copied over:
400
+ e.lengthComputable = oe.lengthComputable;
401
+ e.loaded = oe.loaded;
402
+ e.total = oe.total;
403
+ that._onProgress(e, options);
404
+ });
405
+ options.xhr = function () {
406
+ return xhr;
407
+ };
408
+ }
409
+ },
410
+
411
+ _isInstanceOf: function (type, obj) {
412
+ // Cross-frame instanceof check
413
+ return Object.prototype.toString.call(obj) === '[object ' + type + ']';
414
+ },
415
+
416
+ _initXHRData: function (options) {
417
+ var that = this,
418
+ formData,
419
+ file = options.files[0],
420
+ // Ignore non-multipart setting if not supported:
421
+ multipart = options.multipart || !$.support.xhrFileUpload,
422
+ paramName = options.paramName[0];
423
+ options.headers = $.extend({}, options.headers);
424
+ if (options.contentRange) {
425
+ options.headers['Content-Range'] = options.contentRange;
426
+ }
427
+ if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
428
+ options.headers['Content-Disposition'] = 'attachment; filename="' +
429
+ encodeURI(file.name) + '"';
430
+ }
431
+ if (!multipart) {
432
+ options.contentType = file.type;
433
+ options.data = options.blob || file;
434
+ } else if ($.support.xhrFormDataFileUpload) {
435
+ if (options.postMessage) {
436
+ // window.postMessage does not allow sending FormData
437
+ // objects, so we just add the File/Blob objects to
438
+ // the formData array and let the postMessage window
439
+ // create the FormData object out of this array:
440
+ formData = this._getFormData(options);
441
+ if (options.blob) {
442
+ formData.push({
443
+ name: paramName,
444
+ value: options.blob
445
+ });
446
+ } else {
447
+ $.each(options.files, function (index, file) {
448
+ formData.push({
449
+ name: options.paramName[index] || paramName,
450
+ value: file
451
+ });
452
+ });
453
+ }
454
+ } else {
455
+ if (that._isInstanceOf('FormData', options.formData)) {
456
+ formData = options.formData;
457
+ } else {
458
+ formData = new FormData();
459
+ $.each(this._getFormData(options), function (index, field) {
460
+ formData.append(field.name, field.value);
461
+ });
462
+ }
463
+ if (options.blob) {
464
+ formData.append(paramName, options.blob, file.name);
465
+ } else {
466
+ $.each(options.files, function (index, file) {
467
+ // This check allows the tests to run with
468
+ // dummy objects:
469
+ if (that._isInstanceOf('File', file) ||
470
+ that._isInstanceOf('Blob', file)) {
471
+ formData.append(
472
+ options.paramName[index] || paramName,
473
+ file,
474
+ file.uploadName || file.name
475
+ );
476
+ }
477
+ });
478
+ }
479
+ }
480
+ options.data = formData;
481
+ }
482
+ // Blob reference is not needed anymore, free memory:
483
+ options.blob = null;
484
+ },
485
+
486
+ _initIframeSettings: function (options) {
487
+ var targetHost = $('<a></a>').prop('href', options.url).prop('host');
488
+ // Setting the dataType to iframe enables the iframe transport:
489
+ options.dataType = 'iframe ' + (options.dataType || '');
490
+ // The iframe transport accepts a serialized array as form data:
491
+ options.formData = this._getFormData(options);
492
+ // Add redirect url to form data on cross-domain uploads:
493
+ if (options.redirect && targetHost && targetHost !== location.host) {
494
+ options.formData.push({
495
+ name: options.redirectParamName || 'redirect',
496
+ value: options.redirect
497
+ });
498
+ }
499
+ },
500
+
501
+ _initDataSettings: function (options) {
502
+ if (this._isXHRUpload(options)) {
503
+ if (!this._chunkedUpload(options, true)) {
504
+ if (!options.data) {
505
+ this._initXHRData(options);
506
+ }
507
+ this._initProgressListener(options);
508
+ }
509
+ if (options.postMessage) {
510
+ // Setting the dataType to postmessage enables the
511
+ // postMessage transport:
512
+ options.dataType = 'postmessage ' + (options.dataType || '');
513
+ }
514
+ } else {
515
+ this._initIframeSettings(options);
516
+ }
517
+ },
518
+
519
+ _getParamName: function (options) {
520
+ var fileInput = $(options.fileInput),
521
+ paramName = options.paramName;
522
+ if (!paramName) {
523
+ paramName = [];
524
+ fileInput.each(function () {
525
+ var input = $(this),
526
+ name = input.prop('name') || 'files[]',
527
+ i = (input.prop('files') || [1]).length;
528
+ while (i) {
529
+ paramName.push(name);
530
+ i -= 1;
531
+ }
532
+ });
533
+ if (!paramName.length) {
534
+ paramName = [fileInput.prop('name') || 'files[]'];
535
+ }
536
+ } else if (!$.isArray(paramName)) {
537
+ paramName = [paramName];
538
+ }
539
+ return paramName;
540
+ },
541
+
542
+ _initFormSettings: function (options) {
543
+ // Retrieve missing options from the input field and the
544
+ // associated form, if available:
545
+ if (!options.form || !options.form.length) {
546
+ options.form = $(options.fileInput.prop('form'));
547
+ // If the given file input doesn't have an associated form,
548
+ // use the default widget file input's form:
549
+ if (!options.form.length) {
550
+ options.form = $(this.options.fileInput.prop('form'));
551
+ }
552
+ }
553
+ options.paramName = this._getParamName(options);
554
+ if (!options.url) {
555
+ options.url = options.form.prop('action') || location.href;
556
+ }
557
+ // The HTTP request method must be "POST" or "PUT":
558
+ options.type = (options.type ||
559
+ ($.type(options.form.prop('method')) === 'string' &&
560
+ options.form.prop('method')) || ''
561
+ ).toUpperCase();
562
+ if (options.type !== 'POST' && options.type !== 'PUT' &&
563
+ options.type !== 'PATCH') {
564
+ options.type = 'POST';
565
+ }
566
+ if (!options.formAcceptCharset) {
567
+ options.formAcceptCharset = options.form.attr('accept-charset');
568
+ }
569
+ },
570
+
571
+ _getAJAXSettings: function (data) {
572
+ var options = $.extend({}, this.options, data);
573
+ this._initFormSettings(options);
574
+ this._initDataSettings(options);
575
+ return options;
576
+ },
577
+
578
+ // jQuery 1.6 doesn't provide .state(),
579
+ // while jQuery 1.8+ removed .isRejected() and .isResolved():
580
+ _getDeferredState: function (deferred) {
581
+ if (deferred.state) {
582
+ return deferred.state();
583
+ }
584
+ if (deferred.isResolved()) {
585
+ return 'resolved';
586
+ }
587
+ if (deferred.isRejected()) {
588
+ return 'rejected';
589
+ }
590
+ return 'pending';
591
+ },
592
+
593
+ // Maps jqXHR callbacks to the equivalent
594
+ // methods of the given Promise object:
595
+ _enhancePromise: function (promise) {
596
+ promise.success = promise.done;
597
+ promise.error = promise.fail;
598
+ promise.complete = promise.always;
599
+ return promise;
600
+ },
601
+
602
+ // Creates and returns a Promise object enhanced with
603
+ // the jqXHR methods abort, success, error and complete:
604
+ _getXHRPromise: function (resolveOrReject, context, args) {
605
+ var dfd = $.Deferred(),
606
+ promise = dfd.promise();
607
+ context = context || this.options.context || promise;
608
+ if (resolveOrReject === true) {
609
+ dfd.resolveWith(context, args);
610
+ } else if (resolveOrReject === false) {
611
+ dfd.rejectWith(context, args);
612
+ }
613
+ promise.abort = dfd.promise;
614
+ return this._enhancePromise(promise);
615
+ },
616
+
617
+ // Adds convenience methods to the data callback argument:
618
+ _addConvenienceMethods: function (e, data) {
619
+ var that = this,
620
+ getPromise = function (args) {
621
+ return $.Deferred().resolveWith(that, args).promise();
622
+ };
623
+ data.process = function (resolveFunc, rejectFunc) {
624
+ if (resolveFunc || rejectFunc) {
625
+ data._processQueue = this._processQueue =
626
+ (this._processQueue || getPromise([this])).pipe(
627
+ function () {
628
+ if (data.errorThrown) {
629
+ return $.Deferred()
630
+ .rejectWith(that, [data]).promise();
631
+ }
632
+ return getPromise(arguments);
633
+ }
634
+ ).pipe(resolveFunc, rejectFunc);
635
+ }
636
+ return this._processQueue || getPromise([this]);
637
+ };
638
+ data.submit = function () {
639
+ if (this.state() !== 'pending') {
640
+ data.jqXHR = this.jqXHR =
641
+ (that._trigger(
642
+ 'submit',
643
+ $.Event('submit', {delegatedEvent: e}),
644
+ this
645
+ ) !== false) && that._onSend(e, this);
646
+ }
647
+ return this.jqXHR || that._getXHRPromise();
648
+ };
649
+ data.abort = function () {
650
+ if (this.jqXHR) {
651
+ return this.jqXHR.abort();
652
+ }
653
+ this.errorThrown = 'abort';
654
+ return that._getXHRPromise();
655
+ };
656
+ data.state = function () {
657
+ if (this.jqXHR) {
658
+ return that._getDeferredState(this.jqXHR);
659
+ }
660
+ if (this._processQueue) {
661
+ return that._getDeferredState(this._processQueue);
662
+ }
663
+ };
664
+ data.processing = function () {
665
+ return !this.jqXHR && this._processQueue && that
666
+ ._getDeferredState(this._processQueue) === 'pending';
667
+ };
668
+ data.progress = function () {
669
+ return this._progress;
670
+ };
671
+ data.response = function () {
672
+ return this._response;
673
+ };
674
+ },
675
+
676
+ // Parses the Range header from the server response
677
+ // and returns the uploaded bytes:
678
+ _getUploadedBytes: function (jqXHR) {
679
+ var range = jqXHR.getResponseHeader('Range'),
680
+ parts = range && range.split('-'),
681
+ upperBytesPos = parts && parts.length > 1 &&
682
+ parseInt(parts[1], 10);
683
+ return upperBytesPos && upperBytesPos + 1;
684
+ },
685
+
686
+ // Uploads a file in multiple, sequential requests
687
+ // by splitting the file up in multiple blob chunks.
688
+ // If the second parameter is true, only tests if the file
689
+ // should be uploaded in chunks, but does not invoke any
690
+ // upload requests:
691
+ _chunkedUpload: function (options, testOnly) {
692
+ options.uploadedBytes = options.uploadedBytes || 0;
693
+ var that = this,
694
+ file = options.files[0],
695
+ fs = file.size,
696
+ ub = options.uploadedBytes,
697
+ mcs = options.maxChunkSize || fs,
698
+ slice = this._blobSlice,
699
+ dfd = $.Deferred(),
700
+ promise = dfd.promise(),
701
+ jqXHR,
702
+ upload;
703
+ if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
704
+ options.data) {
705
+ return false;
706
+ }
707
+ if (testOnly) {
708
+ return true;
709
+ }
710
+ if (ub >= fs) {
711
+ file.error = options.i18n('uploadedBytes');
712
+ return this._getXHRPromise(
713
+ false,
714
+ options.context,
715
+ [null, 'error', file.error]
716
+ );
717
+ }
718
+ // The chunk upload method:
719
+ upload = function () {
720
+ // Clone the options object for each chunk upload:
721
+ var o = $.extend({}, options),
722
+ currentLoaded = o._progress.loaded;
723
+ o.blob = slice.call(
724
+ file,
725
+ ub,
726
+ ub + mcs,
727
+ file.type
728
+ );
729
+ // Store the current chunk size, as the blob itself
730
+ // will be dereferenced after data processing:
731
+ o.chunkSize = o.blob.size;
732
+ // Expose the chunk bytes position range:
733
+ o.contentRange = 'bytes ' + ub + '-' +
734
+ (ub + o.chunkSize - 1) + '/' + fs;
735
+ // Process the upload data (the blob and potential form data):
736
+ that._initXHRData(o);
737
+ // Add progress listeners for this chunk upload:
738
+ that._initProgressListener(o);
739
+ jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
740
+ that._getXHRPromise(false, o.context))
741
+ .done(function (result, textStatus, jqXHR) {
742
+ ub = that._getUploadedBytes(jqXHR) ||
743
+ (ub + o.chunkSize);
744
+ // Create a progress event if no final progress event
745
+ // with loaded equaling total has been triggered
746
+ // for this chunk:
747
+ if (currentLoaded + o.chunkSize - o._progress.loaded) {
748
+ that._onProgress($.Event('progress', {
749
+ lengthComputable: true,
750
+ loaded: ub - o.uploadedBytes,
751
+ total: ub - o.uploadedBytes
752
+ }), o);
753
+ }
754
+ options.uploadedBytes = o.uploadedBytes = ub;
755
+ o.result = result;
756
+ o.textStatus = textStatus;
757
+ o.jqXHR = jqXHR;
758
+ that._trigger('chunkdone', null, o);
759
+ that._trigger('chunkalways', null, o);
760
+ if (ub < fs) {
761
+ // File upload not yet complete,
762
+ // continue with the next chunk:
763
+ upload();
764
+ } else {
765
+ dfd.resolveWith(
766
+ o.context,
767
+ [result, textStatus, jqXHR]
768
+ );
769
+ }
770
+ })
771
+ .fail(function (jqXHR, textStatus, errorThrown) {
772
+ o.jqXHR = jqXHR;
773
+ o.textStatus = textStatus;
774
+ o.errorThrown = errorThrown;
775
+ that._trigger('chunkfail', null, o);
776
+ that._trigger('chunkalways', null, o);
777
+ dfd.rejectWith(
778
+ o.context,
779
+ [jqXHR, textStatus, errorThrown]
780
+ );
781
+ });
782
+ };
783
+ this._enhancePromise(promise);
784
+ promise.abort = function () {
785
+ return jqXHR.abort();
786
+ };
787
+ upload();
788
+ return promise;
789
+ },
790
+
791
+ _beforeSend: function (e, data) {
792
+ if (this._active === 0) {
793
+ // the start callback is triggered when an upload starts
794
+ // and no other uploads are currently running,
795
+ // equivalent to the global ajaxStart event:
796
+ this._trigger('start');
797
+ // Set timer for global bitrate progress calculation:
798
+ this._bitrateTimer = new this._BitrateTimer();
799
+ // Reset the global progress values:
800
+ this._progress.loaded = this._progress.total = 0;
801
+ this._progress.bitrate = 0;
802
+ }
803
+ // Make sure the container objects for the .response() and
804
+ // .progress() methods on the data object are available
805
+ // and reset to their initial state:
806
+ this._initResponseObject(data);
807
+ this._initProgressObject(data);
808
+ data._progress.loaded = data.loaded = data.uploadedBytes || 0;
809
+ data._progress.total = data.total = this._getTotal(data.files) || 1;
810
+ data._progress.bitrate = data.bitrate = 0;
811
+ this._active += 1;
812
+ // Initialize the global progress values:
813
+ this._progress.loaded += data.loaded;
814
+ this._progress.total += data.total;
815
+ },
816
+
817
+ _onDone: function (result, textStatus, jqXHR, options) {
818
+ var total = options._progress.total,
819
+ response = options._response;
820
+ if (options._progress.loaded < total) {
821
+ // Create a progress event if no final progress event
822
+ // with loaded equaling total has been triggered:
823
+ this._onProgress($.Event('progress', {
824
+ lengthComputable: true,
825
+ loaded: total,
826
+ total: total
827
+ }), options);
828
+ }
829
+ response.result = options.result = result;
830
+ response.textStatus = options.textStatus = textStatus;
831
+ response.jqXHR = options.jqXHR = jqXHR;
832
+ this._trigger('done', null, options);
833
+ },
834
+
835
+ _onFail: function (jqXHR, textStatus, errorThrown, options) {
836
+ var response = options._response;
837
+ if (options.recalculateProgress) {
838
+ // Remove the failed (error or abort) file upload from
839
+ // the global progress calculation:
840
+ this._progress.loaded -= options._progress.loaded;
841
+ this._progress.total -= options._progress.total;
842
+ }
843
+ response.jqXHR = options.jqXHR = jqXHR;
844
+ response.textStatus = options.textStatus = textStatus;
845
+ response.errorThrown = options.errorThrown = errorThrown;
846
+ this._trigger('fail', null, options);
847
+ },
848
+
849
+ _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
850
+ // jqXHRorResult, textStatus and jqXHRorError are added to the
851
+ // options object via done and fail callbacks
852
+ this._trigger('always', null, options);
853
+ },
854
+
855
+ _onSend: function (e, data) {
856
+ if (!data.submit) {
857
+ this._addConvenienceMethods(e, data);
858
+ }
859
+ var that = this,
860
+ jqXHR,
861
+ aborted,
862
+ slot,
863
+ pipe,
864
+ options = that._getAJAXSettings(data),
865
+ send = function () {
866
+ that._sending += 1;
867
+ // Set timer for bitrate progress calculation:
868
+ options._bitrateTimer = new that._BitrateTimer();
869
+ jqXHR = jqXHR || (
870
+ ((aborted || that._trigger(
871
+ 'send',
872
+ $.Event('send', {delegatedEvent: e}),
873
+ options
874
+ ) === false) &&
875
+ that._getXHRPromise(false, options.context, aborted)) ||
876
+ that._chunkedUpload(options) || $.ajax(options)
877
+ ).done(function (result, textStatus, jqXHR) {
878
+ that._onDone(result, textStatus, jqXHR, options);
879
+ }).fail(function (jqXHR, textStatus, errorThrown) {
880
+ that._onFail(jqXHR, textStatus, errorThrown, options);
881
+ }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
882
+ that._onAlways(
883
+ jqXHRorResult,
884
+ textStatus,
885
+ jqXHRorError,
886
+ options
887
+ );
888
+ that._sending -= 1;
889
+ that._active -= 1;
890
+ if (options.limitConcurrentUploads &&
891
+ options.limitConcurrentUploads > that._sending) {
892
+ // Start the next queued upload,
893
+ // that has not been aborted:
894
+ var nextSlot = that._slots.shift();
895
+ while (nextSlot) {
896
+ if (that._getDeferredState(nextSlot) === 'pending') {
897
+ nextSlot.resolve();
898
+ break;
899
+ }
900
+ nextSlot = that._slots.shift();
901
+ }
902
+ }
903
+ if (that._active === 0) {
904
+ // The stop callback is triggered when all uploads have
905
+ // been completed, equivalent to the global ajaxStop event:
906
+ that._trigger('stop');
907
+ }
908
+ });
909
+ return jqXHR;
910
+ };
911
+ this._beforeSend(e, options);
912
+ if (this.options.sequentialUploads ||
913
+ (this.options.limitConcurrentUploads &&
914
+ this.options.limitConcurrentUploads <= this._sending)) {
915
+ if (this.options.limitConcurrentUploads > 1) {
916
+ slot = $.Deferred();
917
+ this._slots.push(slot);
918
+ pipe = slot.pipe(send);
919
+ } else {
920
+ this._sequence = this._sequence.pipe(send, send);
921
+ pipe = this._sequence;
922
+ }
923
+ // Return the piped Promise object, enhanced with an abort method,
924
+ // which is delegated to the jqXHR object of the current upload,
925
+ // and jqXHR callbacks mapped to the equivalent Promise methods:
926
+ pipe.abort = function () {
927
+ aborted = [undefined, 'abort', 'abort'];
928
+ if (!jqXHR) {
929
+ if (slot) {
930
+ slot.rejectWith(options.context, aborted);
931
+ }
932
+ return send();
933
+ }
934
+ return jqXHR.abort();
935
+ };
936
+ return this._enhancePromise(pipe);
937
+ }
938
+ return send();
939
+ },
940
+
941
+ _onAdd: function (e, data) {
942
+ var that = this,
943
+ result = true,
944
+ options = $.extend({}, this.options, data),
945
+ files = data.files,
946
+ filesLength = files.length,
947
+ limit = options.limitMultiFileUploads,
948
+ limitSize = options.limitMultiFileUploadSize,
949
+ overhead = options.limitMultiFileUploadSizeOverhead,
950
+ batchSize = 0,
951
+ paramName = this._getParamName(options),
952
+ paramNameSet,
953
+ paramNameSlice,
954
+ fileSet,
955
+ i,
956
+ j = 0;
957
+ if (limitSize && (!filesLength || files[0].size === undefined)) {
958
+ limitSize = undefined;
959
+ }
960
+ if (!(options.singleFileUploads || limit || limitSize) ||
961
+ !this._isXHRUpload(options)) {
962
+ fileSet = [files];
963
+ paramNameSet = [paramName];
964
+ } else if (!(options.singleFileUploads || limitSize) && limit) {
965
+ fileSet = [];
966
+ paramNameSet = [];
967
+ for (i = 0; i < filesLength; i += limit) {
968
+ fileSet.push(files.slice(i, i + limit));
969
+ paramNameSlice = paramName.slice(i, i + limit);
970
+ if (!paramNameSlice.length) {
971
+ paramNameSlice = paramName;
972
+ }
973
+ paramNameSet.push(paramNameSlice);
974
+ }
975
+ } else if (!options.singleFileUploads && limitSize) {
976
+ fileSet = [];
977
+ paramNameSet = [];
978
+ for (i = 0; i < filesLength; i = i + 1) {
979
+ batchSize += files[i].size + overhead;
980
+ if (i + 1 === filesLength ||
981
+ (batchSize + files[i + 1].size + overhead) >
982
+ limitSize) {
983
+ fileSet.push(files.slice(j, i + 1));
984
+ paramNameSlice = paramName.slice(j, i + 1);
985
+ if (!paramNameSlice.length) {
986
+ paramNameSlice = paramName;
987
+ }
988
+ paramNameSet.push(paramNameSlice);
989
+ j = i + 1;
990
+ batchSize = 0;
991
+ }
992
+ }
993
+ } else {
994
+ paramNameSet = paramName;
995
+ }
996
+ data.originalFiles = files;
997
+ $.each(fileSet || files, function (index, element) {
998
+ var newData = $.extend({}, data);
999
+ newData.files = fileSet ? element : [element];
1000
+ newData.paramName = paramNameSet[index];
1001
+ that._initResponseObject(newData);
1002
+ that._initProgressObject(newData);
1003
+ that._addConvenienceMethods(e, newData);
1004
+ result = that._trigger(
1005
+ 'add',
1006
+ $.Event('add', {delegatedEvent: e}),
1007
+ newData
1008
+ );
1009
+ return result;
1010
+ });
1011
+ return result;
1012
+ },
1013
+
1014
+ _replaceFileInput: function (input) {
1015
+ var inputClone = input.clone(true);
1016
+ $('<form></form>').append(inputClone)[0].reset();
1017
+ // Detaching allows to insert the fileInput on another form
1018
+ // without loosing the file input value:
1019
+ input.after(inputClone).detach();
1020
+ // Avoid memory leaks with the detached file input:
1021
+ $.cleanData(input.unbind('remove'));
1022
+ // Replace the original file input element in the fileInput
1023
+ // elements set with the clone, which has been copied including
1024
+ // event handlers:
1025
+ this.options.fileInput = this.options.fileInput.map(function (i, el) {
1026
+ if (el === input[0]) {
1027
+ return inputClone[0];
1028
+ }
1029
+ return el;
1030
+ });
1031
+ // If the widget has been initialized on the file input itself,
1032
+ // override this.element with the file input clone:
1033
+ if (input[0] === this.element[0]) {
1034
+ this.element = inputClone;
1035
+ }
1036
+ },
1037
+
1038
+ _handleFileTreeEntry: function (entry, path) {
1039
+ var that = this,
1040
+ dfd = $.Deferred(),
1041
+ errorHandler = function (e) {
1042
+ if (e && !e.entry) {
1043
+ e.entry = entry;
1044
+ }
1045
+ // Since $.when returns immediately if one
1046
+ // Deferred is rejected, we use resolve instead.
1047
+ // This allows valid files and invalid items
1048
+ // to be returned together in one set:
1049
+ dfd.resolve([e]);
1050
+ },
1051
+ dirReader;
1052
+ path = path || '';
1053
+ if (entry.isFile) {
1054
+ if (entry._file) {
1055
+ // Workaround for Chrome bug #149735
1056
+ entry._file.relativePath = path;
1057
+ dfd.resolve(entry._file);
1058
+ } else {
1059
+ entry.file(function (file) {
1060
+ file.relativePath = path;
1061
+ dfd.resolve(file);
1062
+ }, errorHandler);
1063
+ }
1064
+ } else if (entry.isDirectory) {
1065
+ dirReader = entry.createReader();
1066
+ dirReader.readEntries(function (entries) {
1067
+ that._handleFileTreeEntries(
1068
+ entries,
1069
+ path + entry.name + '/'
1070
+ ).done(function (files) {
1071
+ dfd.resolve(files);
1072
+ }).fail(errorHandler);
1073
+ }, errorHandler);
1074
+ } else {
1075
+ // Return an empy list for file system items
1076
+ // other than files or directories:
1077
+ dfd.resolve([]);
1078
+ }
1079
+ return dfd.promise();
1080
+ },
1081
+
1082
+ _handleFileTreeEntries: function (entries, path) {
1083
+ var that = this;
1084
+ return $.when.apply(
1085
+ $,
1086
+ $.map(entries, function (entry) {
1087
+ return that._handleFileTreeEntry(entry, path);
1088
+ })
1089
+ ).pipe(function () {
1090
+ return Array.prototype.concat.apply(
1091
+ [],
1092
+ arguments
1093
+ );
1094
+ });
1095
+ },
1096
+
1097
+ _getDroppedFiles: function (dataTransfer) {
1098
+ dataTransfer = dataTransfer || {};
1099
+ var items = dataTransfer.items;
1100
+ if (items && items.length && (items[0].webkitGetAsEntry ||
1101
+ items[0].getAsEntry)) {
1102
+ return this._handleFileTreeEntries(
1103
+ $.map(items, function (item) {
1104
+ var entry;
1105
+ if (item.webkitGetAsEntry) {
1106
+ entry = item.webkitGetAsEntry();
1107
+ if (entry) {
1108
+ // Workaround for Chrome bug #149735:
1109
+ entry._file = item.getAsFile();
1110
+ }
1111
+ return entry;
1112
+ }
1113
+ return item.getAsEntry();
1114
+ })
1115
+ );
1116
+ }
1117
+ return $.Deferred().resolve(
1118
+ $.makeArray(dataTransfer.files)
1119
+ ).promise();
1120
+ },
1121
+
1122
+ _getSingleFileInputFiles: function (fileInput) {
1123
+ fileInput = $(fileInput);
1124
+ var entries = fileInput.prop('webkitEntries') ||
1125
+ fileInput.prop('entries'),
1126
+ files,
1127
+ value;
1128
+ if (entries && entries.length) {
1129
+ return this._handleFileTreeEntries(entries);
1130
+ }
1131
+ files = $.makeArray(fileInput.prop('files'));
1132
+ if (!files.length) {
1133
+ value = fileInput.prop('value');
1134
+ if (!value) {
1135
+ return $.Deferred().resolve([]).promise();
1136
+ }
1137
+ // If the files property is not available, the browser does not
1138
+ // support the File API and we add a pseudo File object with
1139
+ // the input value as name with path information removed:
1140
+ files = [{name: value.replace(/^.*\\/, '')}];
1141
+ } else if (files[0].name === undefined && files[0].fileName) {
1142
+ // File normalization for Safari 4 and Firefox 3:
1143
+ $.each(files, function (index, file) {
1144
+ file.name = file.fileName;
1145
+ file.size = file.fileSize;
1146
+ });
1147
+ }
1148
+ return $.Deferred().resolve(files).promise();
1149
+ },
1150
+
1151
+ _getFileInputFiles: function (fileInput) {
1152
+ if (!(fileInput instanceof $) || fileInput.length === 1) {
1153
+ return this._getSingleFileInputFiles(fileInput);
1154
+ }
1155
+ return $.when.apply(
1156
+ $,
1157
+ $.map(fileInput, this._getSingleFileInputFiles)
1158
+ ).pipe(function () {
1159
+ return Array.prototype.concat.apply(
1160
+ [],
1161
+ arguments
1162
+ );
1163
+ });
1164
+ },
1165
+
1166
+ _onChange: function (e) {
1167
+ var that = this,
1168
+ data = {
1169
+ fileInput: $(e.target),
1170
+ form: $(e.target.form)
1171
+ };
1172
+ this._getFileInputFiles(data.fileInput).always(function (files) {
1173
+ data.files = files;
1174
+ if (that.options.replaceFileInput) {
1175
+ that._replaceFileInput(data.fileInput);
1176
+ }
1177
+ if (that._trigger(
1178
+ 'change',
1179
+ $.Event('change', {delegatedEvent: e}),
1180
+ data
1181
+ ) !== false) {
1182
+ that._onAdd(e, data);
1183
+ }
1184
+ });
1185
+ },
1186
+
1187
+ _onPaste: function (e) {
1188
+ var items = e.originalEvent && e.originalEvent.clipboardData &&
1189
+ e.originalEvent.clipboardData.items,
1190
+ data = {files: []};
1191
+ if (items && items.length) {
1192
+ $.each(items, function (index, item) {
1193
+ var file = item.getAsFile && item.getAsFile();
1194
+ if (file) {
1195
+ data.files.push(file);
1196
+ }
1197
+ });
1198
+ if (this._trigger(
1199
+ 'paste',
1200
+ $.Event('paste', {delegatedEvent: e}),
1201
+ data
1202
+ ) !== false) {
1203
+ this._onAdd(e, data);
1204
+ }
1205
+ }
1206
+ },
1207
+
1208
+ _onDrop: function (e) {
1209
+ e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
1210
+ var that = this,
1211
+ dataTransfer = e.dataTransfer,
1212
+ data = {};
1213
+ if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
1214
+ e.preventDefault();
1215
+ this._getDroppedFiles(dataTransfer).always(function (files) {
1216
+ data.files = files;
1217
+ if (that._trigger(
1218
+ 'drop',
1219
+ $.Event('drop', {delegatedEvent: e}),
1220
+ data
1221
+ ) !== false) {
1222
+ that._onAdd(e, data);
1223
+ }
1224
+ });
1225
+ }
1226
+ },
1227
+
1228
+ _onDragOver: function (e) {
1229
+ e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
1230
+ var dataTransfer = e.dataTransfer;
1231
+ if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 &&
1232
+ this._trigger(
1233
+ 'dragover',
1234
+ $.Event('dragover', {delegatedEvent: e})
1235
+ ) !== false) {
1236
+ e.preventDefault();
1237
+ dataTransfer.dropEffect = 'copy';
1238
+ }
1239
+ },
1240
+
1241
+ _initEventHandlers: function () {
1242
+ if (this._isXHRUpload(this.options)) {
1243
+ this._on(this.options.dropZone, {
1244
+ dragover: this._onDragOver,
1245
+ drop: this._onDrop
1246
+ });
1247
+ this._on(this.options.pasteZone, {
1248
+ paste: this._onPaste
1249
+ });
1250
+ }
1251
+ if ($.support.fileInput) {
1252
+ this._on(this.options.fileInput, {
1253
+ change: this._onChange
1254
+ });
1255
+ }
1256
+ },
1257
+
1258
+ _destroyEventHandlers: function () {
1259
+ this._off(this.options.dropZone, 'dragover drop');
1260
+ this._off(this.options.pasteZone, 'paste');
1261
+ this._off(this.options.fileInput, 'change');
1262
+ },
1263
+
1264
+ _setOption: function (key, value) {
1265
+ var reinit = $.inArray(key, this._specialOptions) !== -1;
1266
+ if (reinit) {
1267
+ this._destroyEventHandlers();
1268
+ }
1269
+ this._super(key, value);
1270
+ if (reinit) {
1271
+ this._initSpecialOptions();
1272
+ this._initEventHandlers();
1273
+ }
1274
+ },
1275
+
1276
+ _initSpecialOptions: function () {
1277
+ var options = this.options;
1278
+ if (options.fileInput === undefined) {
1279
+ options.fileInput = this.element.is('input[type="file"]') ?
1280
+ this.element : this.element.find('input[type="file"]');
1281
+ } else if (!(options.fileInput instanceof $)) {
1282
+ options.fileInput = $(options.fileInput);
1283
+ }
1284
+ if (!(options.dropZone instanceof $)) {
1285
+ options.dropZone = $(options.dropZone);
1286
+ }
1287
+ if (!(options.pasteZone instanceof $)) {
1288
+ options.pasteZone = $(options.pasteZone);
1289
+ }
1290
+ },
1291
+
1292
+ _getRegExp: function (str) {
1293
+ var parts = str.split('/'),
1294
+ modifiers = parts.pop();
1295
+ parts.shift();
1296
+ return new RegExp(parts.join('/'), modifiers);
1297
+ },
1298
+
1299
+ _isRegExpOption: function (key, value) {
1300
+ return key !== 'url' && $.type(value) === 'string' &&
1301
+ /^\/.*\/[igm]{0,3}$/.test(value);
1302
+ },
1303
+
1304
+ _initDataAttributes: function () {
1305
+ var that = this,
1306
+ options = this.options;
1307
+ // Initialize options set via HTML5 data-attributes:
1308
+ $.each(
1309
+ $(this.element[0].cloneNode(false)).data(),
1310
+ function (key, value) {
1311
+ if (that._isRegExpOption(key, value)) {
1312
+ value = that._getRegExp(value);
1313
+ }
1314
+ options[key] = value;
1315
+ }
1316
+ );
1317
+ },
1318
+
1319
+ _create: function () {
1320
+ this._initDataAttributes();
1321
+ this._initSpecialOptions();
1322
+ this._slots = [];
1323
+ this._sequence = this._getXHRPromise(true);
1324
+ this._sending = this._active = 0;
1325
+ this._initProgressObject(this);
1326
+ this._initEventHandlers();
1327
+ },
1328
+
1329
+ // This method is exposed to the widget API and allows to query
1330
+ // the number of active uploads:
1331
+ active: function () {
1332
+ return this._active;
1333
+ },
1334
+
1335
+ // This method is exposed to the widget API and allows to query
1336
+ // the widget upload progress.
1337
+ // It returns an object with loaded, total and bitrate properties
1338
+ // for the running uploads:
1339
+ progress: function () {
1340
+ return this._progress;
1341
+ },
1342
+
1343
+ // This method is exposed to the widget API and allows adding files
1344
+ // using the fileupload API. The data parameter accepts an object which
1345
+ // must have a files property and can contain additional options:
1346
+ // .fileupload('add', {files: filesList});
1347
+ add: function (data) {
1348
+ var that = this;
1349
+ if (!data || this.options.disabled) {
1350
+ return;
1351
+ }
1352
+ if (data.fileInput && !data.files) {
1353
+ this._getFileInputFiles(data.fileInput).always(function (files) {
1354
+ data.files = files;
1355
+ that._onAdd(null, data);
1356
+ });
1357
+ } else {
1358
+ data.files = $.makeArray(data.files);
1359
+ this._onAdd(null, data);
1360
+ }
1361
+ },
1362
+
1363
+ // This method is exposed to the widget API and allows sending files
1364
+ // using the fileupload API. The data parameter accepts an object which
1365
+ // must have a files or fileInput property and can contain additional options:
1366
+ // .fileupload('send', {files: filesList});
1367
+ // The method returns a Promise object for the file upload call.
1368
+ send: function (data) {
1369
+ if (data && !this.options.disabled) {
1370
+ if (data.fileInput && !data.files) {
1371
+ var that = this,
1372
+ dfd = $.Deferred(),
1373
+ promise = dfd.promise(),
1374
+ jqXHR,
1375
+ aborted;
1376
+ promise.abort = function () {
1377
+ aborted = true;
1378
+ if (jqXHR) {
1379
+ return jqXHR.abort();
1380
+ }
1381
+ dfd.reject(null, 'abort', 'abort');
1382
+ return promise;
1383
+ };
1384
+ this._getFileInputFiles(data.fileInput).always(
1385
+ function (files) {
1386
+ if (aborted) {
1387
+ return;
1388
+ }
1389
+ if (!files.length) {
1390
+ dfd.reject();
1391
+ return;
1392
+ }
1393
+ data.files = files;
1394
+ jqXHR = that._onSend(null, data).then(
1395
+ function (result, textStatus, jqXHR) {
1396
+ dfd.resolve(result, textStatus, jqXHR);
1397
+ },
1398
+ function (jqXHR, textStatus, errorThrown) {
1399
+ dfd.reject(jqXHR, textStatus, errorThrown);
1400
+ }
1401
+ );
1402
+ }
1403
+ );
1404
+ return this._enhancePromise(promise);
1405
+ }
1406
+ data.files = $.makeArray(data.files);
1407
+ if (data.files.length) {
1408
+ return this._onSend(null, data);
1409
+ }
1410
+ }
1411
+ return this._getXHRPromise(false, data && data.context);
1412
+ }
1413
+
1414
+ });
1415
+
1416
+ }));