forked from WebReflection/noSWFUpload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
noswfupload.js
570 lines (540 loc) · 25.5 KB
/
noswfupload.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
(function(className){
var $ = {
/** No SWF Object Multiple File Upload
* @version 1.1.1
* @compatibility Chrome 1, FireFox 3+, Internet Explorer 5+, Opera 8+, Safari 3+
* @author Andrea Giammarchi
* @blog webreflection.blogspot.com
* @license Mit Style License
*/
/**
* @description load dedicated CSS (avoid CSS download for browsers with JavaScript disabled)
* @param String main noswfupload css file (the wrap)
* @param String optional icons file (the list inside the wrap)
* @return Object noswfupload itself
*/
css:function(css, icons){
var head = document.getElementsByTagName("head")[0] || document.documentElement,
style = document.createElement("link");
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("media", "all");
style.setAttribute("href", css);
head.insertBefore(style, head.firstChild);
return icons ? $.css(icons) : $;
},
// DOM event add, del, stop Helper
event:{
/**
* @description add an event via addEventListener or attachEvent
* @param DOMElement the element to add event
* @param String event name without "on" (e.g. "mouseover")
* @param Function the callback to associate as event
* @return Object noswfupload.event
*/
add:document.addEventListener ?
function(node, name, callback){node.addEventListener(name, callback, false);return this;}:
function(node, name, callback){node.attachEvent("on" + name, callback);return this;},
/**
* @description remove an event via removeEventListener or detachEvent
* @param DOMElement the element to remove event
* @param String event name without "on" (e.g. "mouseover")
* @param Function the callback associated as event
* @return Object noswfupload.event
*/
del:document.removeEventListener ?
function(node, name, callback){node.removeEventListener(name, callback, false);return this;}:
function(node, name, callback){node.detachEvent("on" + name, callback);return this;},
/**
* @description to block event propagation and prevent event default
* @param void generated event or undefined
* @return Boolean false
*/
stop:function(e){
if(!e) {
if(self.event)
event.returnValue = !(event.cancelBubble = true);
} else {
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
};
return false;
}
},
/**
* @description to add events to the wrap object, mainly for internal uses
* @param Object generated wrap object
* @return Object the wrap object itself
*/
events:function(wrap){
$.event.add(wrap.dom.input, "change", function(){
lastInput = wrap.dom.input;
$.event.del(wrap.dom.input, "change", arguments.callee);
for(var max = false, input = wrap.dom.input.cloneNode(true), i = 0, files = $.files(wrap.dom.input); i < files.length; i++){
var value = files.item(i).fileName || (files.item(i).fileName = files.item(i).value.split("\\").pop()),
ext = -1 !== value.indexOf(".") ? value.split(".").pop().toLowerCase() : "unknown";
if(wrap.fileType && -1 === wrap.fileType.indexOf("*." + ext)){
max = true;
$.text(
wrap.dom.info,
$.lang.errorType
.replace(/{fileType}/g, wrap.fileType)
.replace(/{fileName}/g, value)
);
} else if(wrap.maxSize !== -1 && files.item(i).fileSize && wrap.maxSize < files.item(i).fileSize){
max = true;
$.text(
wrap.dom.info,
$.lang.errorSize
.replace(/{maxSize}/g, $.size(wrap.maxSize))
.replace(/{fileName}/g, value)
.replace(/{fileSize}/g, $.size(files.item(i).fileSize))
);
} else {
var li = document.createElement("li"),
a = li.appendChild(document.createElement("a"));
wrap.files.unshift(files.item(i));
a.href = "#" + value;
a.alt = a.title = (files.item(i).fileSize ? "[" + $.size(files.item(i).fileSize) + "] " : "") + value;
li.className = ext;
$.text(a, value);
$.event
.add(a, "click", $.empty)
.add(a, "dblclick", files.item(i).remove = (function(li){
return function(e){
for(var i = 0, childNodes = li.parentNode.getElementsByTagName("li"); i < childNodes.length; i++){
if(childNodes[i] === li){
var value = wrap.files[i].fileName;
$.event
.del(li, "click", $.empty)
.del(li, "dblclick", arguments.callee)
;
li.parentNode.removeChild(li);
li = a = null;
wrap.files.splice(i, 1);
$.text(wrap.dom.info, $.lang.removedFile.replace(/{fileName}/g, value));
break;
}
};
return $.empty(e);
};
})(li))
;
if(typeof files.item(i).fileSize != "number")
files.item(i).fileSize = -1;
if(wrap.dom.ul.firstChild)
wrap.dom.ul.insertBefore(li, wrap.dom.ul.firstChild);
else
wrap.dom.ul.appendChild(li);
};
};
input.value = "";
wrap.dom.input.parentNode.replaceChild(input, wrap.dom.input);
wrap.dom.input = input;
if(!max)
$.text(wrap.dom.info, $.lang.removeFile);
$.event.add(wrap.dom.input, "change", arguments.callee);
});
return wrap;
},
/**
* @description used as empty event, mainly for internal uses
* @param void generated event or undefined
* @return Boolean false
*/
empty:function(e){return $.event.stop(e);},
/**
* @description normalize input.files. create if not present, add item method if not present
* @param Object generated wrap object
* @return Object the wrap object itself
*/
files:(function(item){
return function(input){
var files = input.files || [input];
if(!files.item)
files.item = item;
return files;
};
})(function(i){return this[i];}),
// showed message, change for local language messages
// brackets properties are replaced
lang:{
// after one or more file has been added
removeFile:"Double click to remove a file",
// after a file has been removed
removedFile:"File {fileName} removed",
// file over maxSize parameter
errorSize:"WARNING - Maximum size is {maxSize}. File {fileName} is {fileSize}",
// file without a valid type
errorType:"WARNING - File {fileName} has not a valid type: {fileType}"
},
/**
* @description send a single file via XMLHttpRequest, if possible, or iframe in every other case.
* @param Object handler used to perform operations (for example, a wrap Object)
* @param Number optional file maxSize
* @return Object the handler itself
*/
sendFile:(function(toString){
var multipart = function(boundary, name, file){
return "--".concat(
boundary, CRLF,
'Content-Disposition: form-data; name="', name, '"; filename="', file.fileName, '"', CRLF,
"Content-Type: application/octet-stream", CRLF,
CRLF,
file.getAsBinary(), CRLF,
"--", boundary, "--", CRLF
);
},
isFunction = function(Function){return toString.call(Function) === "[object Function]";},
split = "onabort.onerror.onloadstart.onprogress".split("."),
length = split.length,
CRLF = "\r\n",
xhr = this.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP"),
sendFile;
// FireFox 3+, Safari 4 beta (Chrome 2 beta file is buggy and will not work)
if(xhr.upload || xhr.sendAsBinary)
sendFile = function(handler, maxSize){
if(-1 < maxSize && maxSize < handler.file.fileSize){
if(isFunction(handler.onerror))
handler.onerror();
return;
};
for(var
xhr = new XMLHttpRequest,
upload = xhr.upload || {addEventListener:function(event,callback){this["on"+event]=callback}},
i = 0;
i < length;
i++
)
upload.addEventListener(
split[i].substring(2),
(function(event){
return function(rpe){
if(isFunction(handler[event]))
handler[event](rpe, xhr);
};
})(split[i]),
false
);
upload.addEventListener(
"load",
function(rpe){
if(handler.onreadystatechange === false){
if(isFunction(handler.onload))
handler.onload(rpe, xhr);
} else {
setTimeout(function(){
if(xhr.readyState === 4){
if(isFunction(handler.onload))
handler.onload(rpe, xhr);
} else
setTimeout(arguments.callee, 15);
}, 15);
}
},
false
);
xhr.open("post", handler.url, true);
if(!xhr.upload){
var rpe = {loaded:0, total:handler.file.fileSize, simulation:true};
rpe.interval = setInterval(function(){
rpe.loaded += 1024 / 4;
if(rpe.total <= rpe.loaded)
rpe.loaded = rpe.total;
upload.onprogress(rpe);
}, 100);
xhr.onabort = function(){
upload.onabort({});
};
xhr.onerror = function(){
upload.onerror({});
};
xhr.onreadystatechange = function(){
switch(xhr.readyState){
case 2:
case 3:
if(rpe.total <= rpe.loaded)
rpe.loaded = rpe.total;
upload.onprogress(rpe);
break;
case 4:
clearInterval(rpe.interval);
rpe.interval = 0;
rpe.loaded = rpe.total;
upload.onprogress(rpe);
upload[199 < xhr.status && xhr.status < 400 ? "onload" : "onerror"]({});
break;
}
};
upload.onloadstart(rpe);
};
if(handler.file.getAsBinary){
var boundary = "AjaxUploadBoundary" + (new Date).getTime();
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
xhr[xhr.sendAsBinary ? "sendAsBinary" : "send"](multipart(boundary, handler.name, handler.file));
} else {
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-Name", handler.name);
xhr.setRequestHeader("X-Filename", handler.file.fileName);
xhr.send(handler.file);
};
return handler;
};
// Internet Explorer, Opera, others
else
sendFile = function(handler, maxSize){
var url = handler.url.concat(-1 === handler.url.indexOf("?") ? "?" : "&", "AjaxUploadFrame=true"),
rpe = {loaded:1, total:100, simulation:true, interval:setInterval(function(){
if(rpe.loaded < rpe.total)
++rpe.loaded;
if(isFunction(handler.onprogress))
handler.onprogress(rpe, {});
}, 100)},
onload = function(){
iframe.onreadystatechange = iframe.onload = iframe.onerror = null;
form.parentNode.removeChild(form);
form = null;
clearInterval(rpe.interval);
rpe.loaded = rpe.total;
try {
var responseText = (iframe.contentWindow.document || iframe.contentWindow.contentDocument).body.innerHTML;
if(isFunction(handler.onprogress))
handler.onprogress(rpe, {});
if(isFunction(handler.onload))
handler.onload(rpe, {responseText:responseText});
} catch(e) {
if(isFunction(handler.onerror))
handler.onerror(rpe, event || window.event);
}
},
target = ["AjaxUpload", (new Date).getTime(), String(Math.random()).substring(2)].join("_");
try { // IE < 8 does not accept enctype attribute ...
var form = document.createElement('<form enctype="multipart/form-data"></form>'),
iframe = handler.iframe || (handler.iframe = document.createElement('<iframe id="' + target + '" name="' + target + '" src="' + url + '"></iframe>'));
} catch(e) {
var form = document.createElement('form'),
iframe = handler.iframe || (handler.iframe = document.createElement("iframe"));
form.setAttribute("enctype", "multipart/form-data");
iframe.setAttribute("name", iframe.id = target);
iframe.setAttribute("src", url);
};
iframe.style.position = "absolute";
iframe.style.left = iframe.style.top = "-10000px";
iframe.onload = onload;
iframe.onerror = function(event){
if(isFunction(handler.onerror))
handler.onerror(rpe, event || window.event);
};
iframe.onreadystatechange = function(){
if(/loaded|complete/i.test(iframe.readyState))
onload();
else if(isFunction(handler.onloadprogress)){
if(rpe.loaded < rpe.total)
++rpe.loaded;
handler.onloadprogress(rpe, {readyState:{loading:2,interactive:3,loaded:4,complete:4}[iframe.readyState] || 1});
}
};
form.setAttribute("action", handler.url);
form.setAttribute("target", iframe.id);
form.setAttribute("method", "post");
form.appendChild(handler.file);
form.style.display = "none";
if(isFunction(handler.onloadstart))
handler.onloadstart(rpe, {});
with(document.body || document.documentElement){
appendChild(iframe);
appendChild(form).submit();
};
return handler;
};
xhr = null;
return sendFile;
})(Object.prototype.toString),
/**
* @description send a collection of files via sendFile method
* @param Object handler used to perform operations (for example, a wrap Object)
* @param Number optional file maxSize
* @return Object the handler itself
*/
sendFiles:function(handler, maxSize){
var length = handler.files.length,
i = 0,
onload = handler.onload,
onloadstart = handler.onloadstart;
handler.current = 0;
handler.total = 0;
handler.sent = 0;
while(handler.current < length)
handler.total += handler.files[handler.current++].fileSize;
handler.current = 0;
if(length && handler.files[0].fileSize !== -1){
handler.file = handler.files[handler.current];
$.sendFile(handler, maxSize).onload = function(rpe, xhr){
handler.onloadstart = null;
handler.sent += handler.files[handler.current].fileSize;
if(++handler.current < length){
handler.file = handler.files[handler.current];
$.sendFile(handler, maxSize).onload = arguments.callee;
} else if(onload) {
handler.onloadstart = onloadstart;
handler.onload = onload;
handler.onload(rpe, xhr);
}
};
} else if(length) {
handler.total = length * 100;
handler.file = handler.files[handler.current];
$.sendFile(handler, maxSize).onload = function(rpe, xhr){
var callee = arguments.callee;
handler.onloadstart = null;
handler.sent += 100;
if(++handler.current < length){
if(/\b(chrome|safari)\b/i.test(navigator.userAgent)){
handler.iframe.parentNode.removeChild(handler.iframe);
handler.iframe = null;
};
setTimeout(function(){
handler.file = handler.files[handler.current];
$.sendFile(handler, maxSize).onload = callee;
}, 15);
} else if(onload) {
setTimeout(function(){
handler.iframe.parentNode.removeChild(handler.iframe);
handler.iframe = null;
handler.onloadstart = onloadstart;
handler.onload = onload;
handler.onload(rpe, xhr);
}, 15);
}
};
};
return handler;
},
/**
* @description return a human friendly size
* @param Number total bytes
* @return String human friendly size (e.g 1024 === "1.0 Kb")
*/
size:(function(info){
return function(bytes){
var i = 0;
while(1023 < bytes){
bytes /= 1024;
++i;
};
return (i ? bytes.toFixed(2) : bytes) + info[i];
};
})([" bytes", " Kb", " Mb", " Gb", " Tb"]),
/**
* @description add one or more textnode into a DOM element after removing every node, mainly for internal uses.
* @param DOMElement the node to populate with one or more textnodes
*/
text:(function(slice){
return function(node){
arguments = slice.call(arguments, 1);
while(node.firstChild)
node.removeChild(node.firstChild);
while(arguments.length){
node.appendChild(document.createTextNode(arguments.shift()));
if(arguments.length)
node.appendChild(document.createElement("br"));
};
};
})(Array.prototype.slice),
/**
* @description create the wrap node to contain the multiple file upload application.
* Return the wrap object to use for every upload operation.
* @param DOMElement the input type file to wrap to obtain a noswfupload component.
* @param Number optional maxSize for each selected file
*/
wrap:function(input, maxSize){
var wrap = document.createElement("div"),
total = document.createElement("span"),
current = total.cloneNode(true),
ul = document.createElement("ul"),
info = total.cloneNode(true)
;
// be sure input accept multiple files
input.setAttribute("multiple", "multiple");
// created structure swapped with the input
// <div class="noswfupload">
// <input type="file" multiple="multiple" name="{fileName}" />
// <span class="total"></span>
// <span class="current"></span>
// <ul>[
// <li class="{fileExtension}">{fileName}</li>
// ]</ul>
// <span class="info">{customInfo}</span>
// </div>
with(wrap){
appendChild(total);
appendChild(current);
appendChild(ul);
appendChild(info);
};
wrap.className = className;
total.className = "total";
current.className = "current";
info.className = "info";
total.style.visibility = current.style.visibility = "hidden";
wrap.insertBefore(input.parentNode.replaceChild(wrap, input), total);
input.value = "";
// wrap Object
return $.events({
// DOM namespace
dom:{
wrap:wrap, // wrap div
input:input, // input file
total:total, // total bar
current:current, // current bar
ul:ul, // list of files
info:info, // custom info
disabled:false // internal use, checks input file state
},
name:input.name, // name to send for each file ($_FILES[{name}] in the server)
// maxSize is the maximum amount of bytes for each file
maxSize:maxSize ? maxSize >> 0 : -1,
files:[], // file list
// remove every file from the noswfupload component
clean:function(){
while(this.files.length)
this.files[0].remove();
},
// upload one file a time (which make progress possible rather than all files in one shot)
// the handler is an object injected into the wrap one, could be the wrap itself or
// something like {onload:function(){alert("OK")},onerror:function(){alert("Error")}, etc ...}
upload:function(handler){
if(handler){
for(var key in handler)
this[key] = handler[key];
};
$.sendFiles(this, this.maxSize);
return this;
},
// hide progress bar (total + current) and enable files selection
hide:function(){
if(this.dom.disabled){
this.dom.disabled = false;
this.dom.input.removeAttribute("disabled");
};
total.style.visibility = current.style.visibility = "hidden";
},
// show progress bar and disable file selection (used during upload)
// total and current are pixels used to style bars
// totalProp and currentProp are properties to change, "height" by default
show:function(total, current, totalProp, currentProp){
var tstyle = this.dom.total.style,
cstyle = this.dom.current.style;
if(!this.dom.disabled){
this.dom.disabled = true;
this.dom.input.setAttribute("disabled", "disabled");
tstyle.visibility = cstyle.visibility = "";
};
tstyle[totalProp || "height"] = (total >> 0) + "px";
cstyle[currentProp || "height"] = (current >> 0) + "px";
}
});
}
};
// assign the global object
this[className]=$})("noswfupload");