forked from safronizator/damnUploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.damnUploader.js
executable file
·406 lines (365 loc) · 14.3 KB
/
jquery.damnUploader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
(function(window, $) {
var isDefined = function(item) {
return (item !== undefined) && (item != null);
};
// defining compatibility of upload control object
var xhrUploadFlag = false;
if (window.XMLHttpRequest) {
var testXHR = new XMLHttpRequest();
xhrUploadFlag = isDefined(testXHR.upload);
}
// utility object for checking browser compatibility
$.extend($.support, {
fileSelecting: isDefined(window.File) && isDefined(window.FileList),
fileReading: isDefined(window.FileReader),
fileSending: isDefined(window.FormData),
uploadControl: xhrUploadFlag
});
// generates uniq id
var uniq = function(length, prefix) {
length = parseInt(length);
prefix = prefix || '';
if ((length == 0) || isNaN(length)) {
return prefix;
}
var ch = String.fromCharCode(Math.floor(Math.random() * 26) + 97);
return prefix + ch + uniq(--length);
};
// checks that item is File instance or Blob [that have File compatible API]
var checkIsFile = function(item) {
return (item instanceof File) || (item instanceof Blob);
};
// makes blob object with data of defined mime-type
var makeBlob = function(data, mimeType) {
if (window.Blob) {
return new Blob([data], {type: mimeType});
}
var BlobBuilder = (window.MSBlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);
return BlobBuilder ? (new BlobBuilder()).append(ab).getBlob(mimeType) : null;
};
// checks that given argument is dataURI-string
var isDataURI = function(data) {
return data.substr(0, 5) == 'data:';
};
// trying to convert custom data (or dataURI) to Blob
var dataToBlob = function(data) {
data = isDefined(data.toString) ? data.toString() : ("" + data);
var mimeString = "text/plain";
if (isDataURI(data)) {
var pieces = data.split(',');
var byteString = (pieces[0].indexOf('base64') >= 0) ? atob(pieces[1]) : unescape(pieces[1]);
// separate out the mime component
mimeString = pieces[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
data = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(data);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
}
return makeBlob(data, mimeString);
};
// MIME match testing function
var checkMimeMatched = function(mime, accepted) {
var mimeChunks = mime.split('/');
var acceptedChunks = accepted.split('/');
if (mimeChunks[0] != acceptedChunks[0]) {
return false;
}
return (acceptedChunks[1] == '*') || (mimeChunks[1] == acceptedChunks[1]);
};
////////////////////////////////////////////////////////////////////////////
// plugin code
$.fn.damnUploader = function(params) {
if (this.length == 0) {
return this;
} else if (this.length > 1) {
return this.each(function() {
$(this).damnUploader(params);
});
}
// context
var $this = this;
////////////////////////////////////////////////////////////////////////
// initialization
/* default settings */
$this._duSettings = $.extend({
url: '/upload.php',
multiple: true,
fieldName: 'file',
dropping: true,
dropBox: false,
limit: false,
dataType: 'text',
method: 'POST',
acceptType: null
}, params || {});
!$this._duSettings.multiple && ($this._duSettings.limit = 1);
// upload item object
var UploadItem = function(file, completeCallback, progressCallback) {
this.file = file;
this.fieldName = null;
this.replaceName = null;
this.progressCallback = progressCallback;
this.completeCallback = completeCallback;
this.xhr = null;
this.cancelled = false;
this.started = false;
this.completed = false;
this._id = uniq(7);
this._post = [];
};
$.extend(UploadItem.prototype, {
id : function() {
return this._id;
},
addPostData: function(fieldNameOrFieldsArray, value) {
var self = this;
if ($.isArray(fieldNameOrFieldsArray)) {
$.each(fieldNameOrFieldsArray, function(i, item) {
self.addPostData(item.name, item.value);
});
return ;
}
this._post.push({"name" : fieldNameOrFieldsArray, "value" : value});
},
upload: function() {
$this._duUploadItem(this);
},
cancel: function() {
$this.duCancel(this._id);
},
getReaderCallback: function(callback) {
var reader;
if ($.support.fileReading) {
reader = new FileReader();
reader.onload = callback;
}
return reader;
},
readAs: function(as, callback) {
var methodName = 'readAs' + as;
var reader = this.getReaderCallback(callback);
reader && reader[methodName] && reader[methodName].call(reader, this.file);
}
});
// private properties
$this._duQueue = {};
$this._duItemsCount = 0;
// locals
var queue = $this._duQueue;
var set = $this._duSettings;
// private method for items ading
$this._duAddItemsToQueue = function(item) {
var addingEvent = $.Event("du.add");
var limitEvent = $.Event("du.limit");
var ui;
if ($this._duItemsCount === set.limit) {
$this.trigger(limitEvent);
return false;
}
if (item instanceof FileList) {
var ret = [];
$.each(item, function(i, file) {
ret.push($this._duAddItemsToQueue(file));
});
return ret;
} else if ((ui = $this.duNewUploadItem(item)) === false) {
return false;
}
addingEvent.uploadItem = ui;
$this.trigger(addingEvent);
if (addingEvent.isDefaultPrevented()) {
return false;
}
var queueId = ui.id();
$this._duItemsCount++;
queue[queueId] = ui;
return ui;
};
// private file-uploading method
$this._duUploadItem = function(item) {
if (!$.support.fileSending || !checkIsFile(item.file)) {
return false;
}
if (item.started) {
return ;
}
item.started = true;
var xhr = new XMLHttpRequest();
var progress = 0;
var uploaded = false;
var prCall = $.isFunction(item.progressCallback);
if (xhr.upload) {
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
progress = (e.loaded * 100) / e.total;
prCall && item.progressCallback.call(item, Math.round(progress));
}
}, false);
xhr.upload.addEventListener("load", function(e) {
progress = 100;
uploaded = true;
}, false);
} else {
uploaded = true;
}
xhr.onreadystatechange = function() {
var callbackDefined = $.isFunction(item.completeCallback);
if (this.readyState == 4) {
item.completed = true;
if (this.status < 400) {
if (!uploaded) {
callbackDefined && item.completeCallback.call(item, false, null, 0);
} else {
$.isFunction(item.progressCallback) && item.progressCallback.call(item, 100);
var response = set.dataType == 'json' ? $.parseJSON(this.responseText) : this.responseText;
callbackDefined && item.completeCallback.call(item, true, response);
}
} else {
callbackDefined && item.completeCallback.call(item, false, null, this.status);
}
}
};
var filename = item.replaceName || item.file.name;
var method = (set.method.toString().toUpperCase() == 'PUT') ? 'PUT' : 'POST';
xhr.open(method, set.url);
// W3C (IE9, Chrome, Safari, Firefox 4+)
var formData = new FormData();
formData.append((item.fieldName || set.fieldName || 'file'), item.file, filename);
if (item._post.length > 0) {
$.each(item._post, function(i, field) {
formData.append(field.name, field.value);
});
}
xhr.send(formData);
item.xhr = xhr;
}
////////////////////////////////////////////////////////////////////////
// interface elements event handling
var isFileField = (($this.get(0).tagName == 'INPUT') && (this.attr('type') == 'file'));
if (isFileField) {
// Setup file dialog properties
$this.prop('multiple', set.multiple).on('change', function() {
$this._duAddItemsToQueue(this.files);
});
if (set.acceptType !== null) {
$this.attr('accept', set.acceptType);
}
}
if (set.dropping) {
// Setup drag&drop handlers
//TODO: need to review
$this.on('drop', function(e) {
$this._duAddItemsToQueue(e.originalEvent.dataTransfer.files);
return false;
});
set.dropBox && $(set.dropBox).on('drop', function(e) {
$this._duAddItemsToQueue(e.originalEvent.dataTransfer.files);
return false;
});
}
$this.on('du.add', function(e) {
// Checking MIME type
if (set.acceptType === null) {
return;
}
if (e.uploadItem.file) {
if (!checkMimeMatched(e.uploadItem.file.type, set.acceptType)) {
e.preventDefault();
e.stopImmediatePropagation();
}
}
});
////////////////////////////////////////////////////////////////////////
// API control methods
// Start all uploads
$this.duStart = function() {
if (!set.url) {
return $this;
}
$.each(queue, function(queueId, item) {
var compl = item.completeCallback;
item.completeCallback = function(successful, data, error) {
if (!this.cancelled) {
delete queue[queueId];
$this._duItemsCount--;
}
if ($.isFunction(compl)) {
compl.call(this, successful, data, error);
}
if ($this._duItemsCount == 0) {
$this.trigger('du.completed');
}
};
$this._duUploadItem(item);
});
return $this;
};
// Dequeue upload item by it's id
$this.duCancel = function(queueId) {
if (queueId && $this._duItemsCount > 0) {
if (isDefined(queue[queueId])) {
if (queue[queueId].xhr) {
queue[queueId].cancelled = true;
queue[queueId].xhr.abort();
}
delete queue[queueId];
$this._duItemsCount--;
}
}
return $this;
};
// Cancel all uploads & clear queue
$this.duCancelAll = function() {
isFileField && $this.val('');
$.each(queue, function(key, _) {
$this.duCancel(key);
});
return $this;
};
// Creates UploadItem object from File object or from custom data
$this.duNewUploadItem = function(fileOrData) {
switch(true) {
case fileOrData instanceof UploadItem:
return fileOrData;
case checkIsFile(fileOrData):
return new UploadItem(fileOrData);
default:
var blob = dataToBlob(fileOrData);
return (blob !== false) ? $this.duNewUploadItem(blob) : false;
}
};
// Enqueue upload item
$this.duEnqueue = function(item) {
return $this._duAddItemsToQueue(item);
};
// Returns all upload queue
$this.duGetQueue = function() {
return $this._duQueue;
};
// Returns queued items count
$this.duCount = function() {
return $this._duItemsCount;
};
// Change plugin option (url, fieldName, limit, dataType are changeable), or get it value by name
$this.duOption = function(name, value) {
var acceptParams = ['url', 'fieldName', 'limit', 'dataType', 'method'];
if ($.isPlainObject(name)) {
$.each(name, function(key, val) {
$this.duOption(key, val);
});
} else if (value === undefined) {
return $this._duSettings[name];
} else if ($.inArray(name, acceptParams) > -1) {
$this._duSettings[name] = value;
}
return $this;
};
// Check MIME type string for matching acceptType option
$this.duIsAcceptedType = function(mime) {
return (set.acceptType === null) || checkMimeMatched(mime, set.acceptType);
};
return $this;
};
})(window, window.jQuery);