forked from weixiyen/jquery-filedrop
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.dropUpload.js
executable file
·293 lines (244 loc) · 6.75 KB
/
jquery.dropUpload.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
/*
jQuery plugin for drag/drop uploads in HTML5
Author:
Pomle
Email:
Licensed under:
Kopimi, no rights reserved
Project home:
https://github.com/pomle/jquery-dropUpload
Version:
0.5.5
Usage:
See Example.html
*/
(function( $ ){
$.event.props.push("dataTransfer");
var emptyCallback = function() {};
var defaultSettings = {
'fileDropCountMax': null,
'fileMeta': emptyCallback,
'fileParamName': 'dropUploadFile',
'fileSimTransfers': 1,
'fileSizeMax': null,
'onComplete': emptyCallback,
'onDropError': emptyCallback,
'onDropSuccess': emptyCallback,
'onDragEnter': emptyCallback,
'onDragOver': emptyCallback,
'onDragLeave': emptyCallback,
'onFileCompleted': emptyCallback,
'onFileFailed': function(File, message)
{
alert(message);
},
'onFileQueued': emptyCallback,
'onFileSucceeded': emptyCallback,
'onFileStarted': emptyCallback,
'onProgressUpdated': emptyCallback,
'onQueueCompleted': emptyCallback,
'url': ''
};
$.fn.dropUpload = function(method)
{
var settings = {};
var isLoopRunning = false;
var loopSize = 0;
var queue = [];
var eventDrop = function(e)
{
e.preventDefault();
try {
if (!e.dataTransfer.files || e.dataTransfer.files.length == 0) {
throw('FILE_ARRAY_EMPTY');
}
var FileList = e.dataTransfer.files;
if (settings.fileDropCountMax && FileList.length > settings.fileDropCountMax) {
throw('FILE_DROP_COUNT_MAX');
}
settings.onDropSuccess();
filesHandler(FileList);
return true;
}
catch (e) {
settings.onDropError(e.message);
return false;
}
}
var eventDragEnter = function(e)
{
settings.onDragEnter();
}
var eventDragLeave = function(e)
{
settings.onDragLeave();
}
var eventDragOver = function(e)
{
e.preventDefault();
settings.onDragOver();
}
// A method to disable browser default behavior for certian events
var eventKillDefault = function(e)
{
e.preventDefault();
return false;
}
var filesHandler = function(FileList)
{
// Iterate over all files and add to queue if isFileAccepted() returns true
filesIterator(FileList, function(File) {
if (isFileAccepted(File)) {
queueFile(File);
}
});
/*
Engage upload loop if not already running
Notice that it is allowed to start several instances, but it's recommended to control the simultaneous queue length with fileSimTransfers setting
*/
if (!isLoopRunning) {
uploadLoopEngage();
}
}
// Lets us iterate over file lists in a consistent manner
var filesIterator = function(FileList, callback)
{
for (var index = 0; index < FileList.length; index++) {
callback(FileList[index]);
}
return true;
}
// Returns wheater file is an acceptable upload or not
var isFileAccepted = function(File)
{
if (settings.fileSizeMax && (File.size > settings.fileSizeMax)) {
return false;
}
return true;
}
var queueFile = function(File)
{
File.meta = settings.fileMeta() || {}; // If user function returns any data, put it on the File object
queue.push(File);
settings.onFileQueued(File);
}
// This function not totally quirk free as of now
var uploadLoopEngage = function()
{
isLoopRunning = true;
while (queue.length > 0 && loopSize < settings.fileSimTransfers) {
var File = queue.shift();
try {
loopSize++;
// uploadLoopEngage is sent as a callback for when the upload completes so that next file is automatically tried.
uploadFile(File, uploadLoopEngage);
}
catch (e) {
loopSize--;
// Inform plugin about failure
settings.onFileFailed(File, e.message);
settings.onFileCompleted(File);
}
}
isLoopRunning = false;
}
var uploadFile = function(File, onCompleteCallback)
{
//loopSize++;
settings.onFileStarted(File);
var FR = new FileReader();
// Defines the call that is made when upload has completed
var uploadFinished = function()
{
loopSize--;
settings.onProgressUpdated(File, 1);
settings.onFileCompleted(File);
if (typeof onCompleteCallback == 'function') {
onCompleteCallback();
}
if (loopSize == 0) {
settings.onQueueCompleted();
}
}
FR.File = File;
FR.onload = function(e) // Prepares file and meta data for the POST-stream
{
var payload = new FormData();
// Adds Meta data (connected by user defined function fileMeta()
$.each(this.File.meta, function(name, value) {
payload.append(name, value);
});
payload.append(settings.fileParamName, File);
var XHR = new XMLHttpRequest();
XHR.open("POST", settings.url, true); // Perform asynchronous transfer
File.cancel = function()
{
XHR.abort();
uploadFinished();
};
XHR.onerror = function(e)
{
settings.onFileFailed(File);
uploadFinished();
};
XHR.onload = function(e) // Triggers on completed upload
{
settings.onFileSucceeded(File, this.responseText); // reponseText is the response body printed by the server
uploadFinished();
};
XHR.upload.onprogress = function(e)
{
if (e.lengthComputable)
settings.onProgressUpdated(File, e.loaded / e.total);
};
XHR.send(payload);
}
// Initiates reading and puts us in FR.onload on complete
FR.readAsBinaryString(File);
};
var methods = {
init: function( userOptions ) {
settings = $.extend({}, defaultSettings, userOptions);
// I think this is to prevent the browser from opening the file
$(window)
.off('.dropUpload')
.on('drop.dropUpload', eventKillDefault)
.on('dragenter.dropUpload', eventKillDefault)
.on('dragover.dropUpload', eventKillDefault)
.on('dragleave.dropUpload', eventKillDefault)
;
return this.each(function(){
var fileSelect = $('<input type="file" multiple accept="*">');
fileSelect.on("change", function(e) {
filesHandler(this.files);
});
$(this)
.on('click.dropUpload', function(e) { fileSelect.click(); })
.on('drop.dropUpload', eventDrop)
.on('dragover.dropUpload', eventDragOver)
// dragenter and dragleave are inherently buggy and will cause problems with text
.on('dragenter.dropUpload', eventDragEnter)
.on('dragleave.dropUpload', eventDragLeave)
;
});
},
destroy: function()
{
$(window).off('.dropUpload');
return this.each(function(){
$(this).off('.dropUpload');
});
}
};
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.dropUpload' );
}
};
return this;
})( jQuery );