-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsimpleUpload.js
More file actions
1740 lines (1174 loc) · 44.6 KB
/
simpleUpload.js
File metadata and controls
1740 lines (1174 loc) · 44.6 KB
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* simpleUpload.js v.1.1
*
* Copyright 2018, Michael Brook, All rights reserved.
* http://simpleupload.michaelcbrook.com/
*
* simpleUpload.js is an extremely simple yet powerful jQuery file upload plugin.
* It is free to use under the MIT License (http://opensource.org/licenses/MIT)
*
* https://github.com/michaelcbrook/simpleUpload.js
* @michaelcbrook
*/
function simpleUpload(ajax_url, DOM_file, options)
{
var forceIframe = false;
var files = null; //files object for HTML5 uploads (if applicable)
var limit = 0; //the max number of files that can be uploaded from this selection (0 = no limit)
var max_file_size = 0; //max file size for an uploaded file in bytes
var allowed_exts = []; //array of allowed file extensions for an uploaded file
var allowed_types = []; //array of allowed MIME types for an uploaded file
var expect_type = "auto"; //the type of result to expect (can either be auto, json, xml, html, script, or text)
var hash_worker = null; //file path (relative to page) to hash worker javascript file
var on_hash_complete = null; //function(hash, callbacks){ callbacks.proceed(); //success(), proceed(), or error() }; //called when hash is calculated for a file, the next step is determined by the callback that is called
var request_file_name = "file"; //name of file to be uploaded (should be the same as DOM_file's name)
var request_data = {}; //additional data to get passed to the backend script with the file upload
var xhrFields = {}; //object of field name/value pairs to send with ajax request (set on native XHR object) - { withCredentials: true } is one example
//default callback functions
var on_init_callback = function(total_uploads){}; //on initialization of instance, given at least one file is queued for upload (can cancel all uploads or set limit by returning either false or an integer, respectively)
var on_start_callback = function(file){}; //on beginning of each file upload (can return false to exclude this file from being uploaded)
var on_progress_callback = function(progress){}; //on upload progress update
var on_success_callback = function(data){}; //on successful file upload
var on_error_callback = function(error){}; //on failed file upload
var on_cancel_callback = function(){}; //on cancelled upload (via this.upload.cancel())
var on_complete_callback = function(status){}; //on completed upload, regardless of success
var on_finish_callback = function(){}; //on completion of all file uploads for this instance, regardless of success
var on_before_send_callback = function(jqXHR, settings){}; //gives the opportunity to modify the XHR object before sending the request
var upload_contexts = []; //an array containing objects for each file upload that can be referenced inside each callback using "this"
var private_upload_data = []; //same as above, except the properties of these objects are not accessible via "this"
var instance_context = { files: upload_contexts }; //an instance-specific context for "this" to pass to non-file-specific events like init() and finish()
var queued_files = 0; //number of files remaining in the queue for this instance
var hidden_form = null; //jquery object containing hidden form appended to body of page, which contains the moved DOM_file, if it exists
//helper function to run after every success, error, or cancel event
var file_completed = function(upload_num, status){
on_complete(upload_num, status);
queued_files--;
if (queued_files==0)
on_finish();
simpleUpload.activeUploads--;
simpleUpload.uploadNext();
};
/* Wrappers to the callback functions that additionally perform internal functions */
var on_init = function(total_uploads){
return on_init_callback.call(instance_context, total_uploads);
};
var on_start = function(upload_num, file){
if (getUploadState(upload_num) > 0) //if cancelled via the init function, don't start upload
return false;
if (on_start_callback.call(upload_contexts[upload_num], file)===false) { //if start returns false, treat it as a cancellation
setUploadState(upload_num, 4);
return false;
}
if (getUploadState(upload_num) > 0) //if this.upload.cancel() was called inside the start function, don't start upload
return false;
setUploadState(upload_num, 1);
};
var on_progress = function(upload_num, progress){
if (getUploadState(upload_num)==1)
on_progress_callback.call(upload_contexts[upload_num], progress);
};
var on_success = function(upload_num, data){
if (getUploadState(upload_num)==1)
{
setUploadState(upload_num, 2);
on_success_callback.call(upload_contexts[upload_num], data);
file_completed(upload_num, "success");
}
};
var on_error = function(upload_num, error){
if (getUploadState(upload_num)==1)
{
setUploadState(upload_num, 3);
on_error_callback.call(upload_contexts[upload_num], error);
file_completed(upload_num, "error");
}
};
var on_cancel = function(upload_num){
//the this.upload.cancel() function restricts when this can be called
on_cancel_callback.call(upload_contexts[upload_num]);
file_completed(upload_num, "cancel");
};
var on_complete = function(upload_num, status){
on_complete_callback.call(upload_contexts[upload_num], status);
};
var on_finish = function(){
on_finish_callback.call(instance_context);
if (hidden_form!=null)
hidden_form.remove();
};
var on_before_send = function(upload_num, jqXHR, settings){
on_before_send_callback.call(upload_contexts[upload_num], jqXHR, settings);
};
/* End callback wrappers */
/*
* Initialize instance and put uploads in the queue
*/
function create()
{
if (typeof options=="object" && options!==null)
{
if (typeof options.forceIframe=="boolean")
{
forceIframe = options.forceIframe;
}
if (typeof options.init=="function")
{
on_init_callback = options.init;
}
if (typeof options.start=="function")
{
on_start_callback = options.start;
}
if (typeof options.progress=="function")
{
on_progress_callback = options.progress;
}
if (typeof options.success=="function")
{
on_success_callback = options.success;
}
if (typeof options.error=="function")
{
on_error_callback = options.error;
}
if (typeof options.cancel=="function")
{
on_cancel_callback = options.cancel;
}
if (typeof options.complete=="function")
{
on_complete_callback = options.complete;
}
if (typeof options.finish=="function")
{
on_finish_callback = options.finish;
}
if (typeof options.beforeSend=="function")
{
on_before_send_callback = options.beforeSend;
}
if (typeof options.hashWorker=="string" && options.hashWorker!="")
{
hash_worker = options.hashWorker;
}
if (typeof options.hashComplete=="function")
{
on_hash_complete = options.hashComplete;
}
if (typeof options.data=="object" && options.data!==null)
{
for (var x in options.data) //copy each item in case options.data is actually an array
{
request_data[x] = options.data[x];
}
}
if (typeof options.limit=="number" && isInt(options.limit) && options.limit > 0)
{
limit = options.limit;
}
if (typeof options.maxFileSize=="number" && isInt(options.maxFileSize) && options.maxFileSize > 0)
{
max_file_size = options.maxFileSize;
}
if (typeof options.allowedExts=="object" && options.allowedExts!==null)
{
for (var x in options.allowedExts) //ensure allowed_exts stays an array
{
allowed_exts.push(options.allowedExts[x]);
}
}
if (typeof options.allowedTypes=="object" && options.allowedTypes!==null)
{
for (var x in options.allowedTypes) //ensure allowed_types stays an array
{
allowed_types.push(options.allowedTypes[x]);
}
}
if (typeof options.expect=="string" && options.expect!="")
{
var lower_expect = options.expect.toLowerCase();
var valid_expect_types = ["auto", "json", "xml", "html", "script", "text"]; //expect_type must be one of these
for (var x in valid_expect_types)
{
if (valid_expect_types[x]==lower_expect)
{
expect_type = lower_expect;
break;
}
}
}
if (typeof options.xhrFields=="object" && options.xhrFields!==null)
{
for (var x in options.xhrFields) //maintain as object
{
xhrFields[x] = options.xhrFields[x];
}
}
}
if (typeof DOM_file=="object" && DOM_file!==null && DOM_file instanceof jQuery)
{
if (DOM_file.length > 0)
{
DOM_file = DOM_file.get(0); //if DOM_file was passed in as a jquery object, extract its first DOM element and use it instead
}
else
{
return false; //if jquery object was empty, quit now
}
}
if (!forceIframe && window.File && window.FileReader && window.FileList && window.Blob) //check whether browser supports HTML5 File API
{
if (typeof options=="object" && options!==null && typeof options.files=="object" && options.files!==null)
{
files = options.files; //if options.files is defined along with DOM_file, it is the caller's responsibility to make sure they are the same
}
else if (typeof DOM_file=="object" && DOM_file!==null && typeof DOM_file.files=="object" && DOM_file.files!==null)
{
files = DOM_file.files; //fallback on DOM file input if no options.files are given
}
}
if ((typeof DOM_file!="object" || DOM_file===null) && files==null)
{
return false; //we've got nothing to work with, so just quit
}
//request_file_name will be based on (in order of preference) options.name, DOM_file.name, "file"
//if there is an attempt to upload multiple files as an array in one request, restrict it to one file per request, otherwise it will break consistency between ajax and iframe upload methods
if (typeof options=="object" && options!==null && typeof options.name=="string" && options.name!="")
{
request_file_name = options.name.replace(/\[\s*\]/g, '[0]');
}
else if (typeof DOM_file=="object" && DOM_file!==null && typeof DOM_file.name=="string" && DOM_file.name!="")
{
request_file_name = DOM_file.name.replace(/\[\s*\]/g, '[0]');
}
var num_files = 0;
if (files!=null)
{
if (files.length > 0)
{
//the following conditions are necessary in order to do an AJAX upload (minus hashing), so don't start more than one upload if we're certain we'll fallback to the iframe method anyway
if (files.length > 1 && window.FormData && $.ajaxSettings.xhr().upload)
{
if (limit > 0 && files.length > limit) //apply limit if multiple files have been selected
{
num_files = limit;
}
else
{
num_files = files.length;
}
}
else
{
num_files = 1;
}
}
}
else
{
if (DOM_file.value!="")
{
num_files = 1;
}
}
if (num_files > 0)
{
if (typeof DOM_file=="object" && DOM_file!==null)
{
var $DOM_file = $(DOM_file);
hidden_form = $('<form>').hide().attr("enctype", "multipart/form-data").attr("method", "post").appendTo('body');
//move the original file input into the hidden form and create a clone of the original to replace it (clone doesn't retain value)
$DOM_file.after($DOM_file.clone(true).val("")).removeAttr("onchange").off().removeAttr("id").attr("name", request_file_name).appendTo(hidden_form);
}
for (var i = 0; i < num_files; i++)
{
(function(i){
//setting up contextual data...
//not accessible in callbacks directly, but provides data for certain functions that can be run in the callbacks
private_upload_data[i] = {
state: 0, //state of upload in number form (0 = init, 1 = uploading, 2 = success, 3 = error, 4 = cancel)
hashWorker: null, //Worker object from hashing
xhr: null, //jqXHR object from ajax upload
iframe: null //iframe id from iframe upload
};
//this object is accessible via "this" in each file-specific callback (for init and finish, this object is stacked in an array for each file)
upload_contexts[i] = {
upload: {
index: i,
state: "init", //textual form of "state" in private_upload_data
file: (files!=null) ? files[i] : { name: DOM_file.value.split(/(\\|\/)/g).pop() }, //ensure "name" always exists, regardless of HTML5 support
cancel: function(){
if (getUploadState(i)==0) //if upload hasn't started, don't call the callback, just change the state
{
setUploadState(i, 4);
}
else if (getUploadState(i)==1) //cancel if active and call the callback
{
setUploadState(i, 4);
if (private_upload_data[i].hashWorker!=null)
{
private_upload_data[i].hashWorker.terminate();
private_upload_data[i].hashWorker = null;
}
if (private_upload_data[i].xhr!=null)
{
private_upload_data[i].xhr.abort();
private_upload_data[i].xhr = null;
}
if (private_upload_data[i].iframe!=null)
{
$('iframe[name=simpleUpload_iframe_' + private_upload_data[i].iframe + ']').attr("src", "javascript:false;"); //for IE
simpleUpload.dequeueIframe(private_upload_data[i].iframe);
private_upload_data[i].iframe = null;
}
on_cancel(i);
}
else //return false if upload has already completed or been cancelled
{
return false;
}
return true; //cancel was a success
}
}
};
})(i);
}
var init_value = on_init(num_files);
if (init_value!==false)
{
//if the return value of on_init (init_value) is a number, limit the amount of uploads to that number (a value of 0, like false, will cancel all uploads)
var num_files_limit = num_files;
if (typeof init_value=="number" && isInt(init_value) && init_value >= 0 && init_value < num_files)
{
num_files_limit = init_value;
for (var z = num_files_limit; z < num_files; z++)
{
setUploadState(z, 4); //mark each remaining file after the new limit as cancelled
}
}
var remaining_uploads = []; //array of indexes of files to be uploaded from this instance
for (var j = 0; j < num_files_limit; j++)
{
if (on_start(j, upload_contexts[j].upload.file)!==false) //if false is returned, exclude this file from being uploaded
remaining_uploads[remaining_uploads.length] = j;
}
if (remaining_uploads.length > 0)
{
queued_files = remaining_uploads.length;
simpleUpload.queueUpload(remaining_uploads, function(upload_num){
validateFile(upload_num);
});
simpleUpload.uploadNext();
}
else
{
on_finish();
}
}
else //init returned false
{
for (var z in upload_contexts)
{
setUploadState(z, 4); //mark each file as cancelled
}
on_finish();
}
}
}
/*
* Run each file through the validation process
*/
function validateFile(upload_num)
{
if (getUploadState(upload_num)!=1) //stop if upload has been cancelled
return;
var file = null;
if (files!=null) //HTML5
{
if (files[upload_num]!=undefined && files[upload_num]!=null)
{
file = files[upload_num];
}
else //shouldn't happen, unless the files parameter passed in the beginning is not valid, or the passed-by-reference files object has been changed
{
on_error(upload_num, { name: "InternalError", message: "There was an error uploading the file" });
return;
}
}
else
{
if (DOM_file.value=="")
{
on_error(upload_num, { name: "InternalError", message: "There was an error uploading the file" });
return;
}
}
//it's okay for file to be null, which signifies lack of HTML5 support
//if certain information cannot be obtained because of a lack of support via javascript, these checks will return as valid by default, pending server-side checks after uploading
if (allowed_exts.length > 0 && !validateFileExtension(allowed_exts, file))
{
on_error(upload_num, { name: "InvalidFileExtensionError", message: "That file format is not allowed" });
return;
}
if (allowed_types.length > 0 && !validateFileMimeType(allowed_types, file))
{
on_error(upload_num, { name: "InvalidFileTypeError", message: "That file format is not allowed" });
return;
}
if (max_file_size > 0 && !validateFileSize(max_file_size, file))
{
on_error(upload_num, { name: "MaxFileSizeError", message: "That file is too big" });
return;
}
//file passed validation checks
if (hash_worker!=null && on_hash_complete!=null) //if hash worker and hash complete function are present, attempt hashing...
{
hashFile(upload_num);
}
else //skip hashing and continue to upload file...
{
uploadFile(upload_num);
}
}
/*
* If a hash is desired, complete the hashing
*/
function hashFile(upload_num)
{
if (files!=null) //HTML5
{
if (files[upload_num]!=undefined && files[upload_num]!=null)
{
if (window.Worker) //if the Web Workers API is supported (without it, hashing may lock up the browser)
{
var file = files[upload_num];
if (file.size!=undefined && file.size!=null && file.size!="" && isInt(file.size) && (file.slice || file.webkitSlice || file.mozSlice)) //check whether we've got the necessary HTML5 stuff
{
try {
var worker = new Worker(hash_worker);
worker.addEventListener('error', function(event){ //if anything goes wrong, just upload the file
worker.terminate();
private_upload_data[upload_num].hashWorker = null;
uploadFile(upload_num);
}, false);
worker.addEventListener('message', function(event){
if (event.data.result) {
var hash = event.data.result;
worker.terminate();
private_upload_data[upload_num].hashWorker = null;
checkHash(upload_num, hash); //hash was calculated successfully, now go check it
}
}, false);
var buffer_size, block, reader, blob, handle_hash_block, handle_load_block;
handle_load_block = function(event){
worker.postMessage({
'message' : event.target.result,
'block' : block
});
};
handle_hash_block = function(event){
if (block.end !== file.size)
{
block.start += buffer_size;
block.end += buffer_size;
if (block.end > file.size)
{
block.end = file.size;
}
reader = new FileReader();
reader.onload = handle_load_block;
if (file.slice) {
blob = file.slice(block.start, block.end);
} else if (file.webkitSlice) {
blob = file.webkitSlice(block.start, block.end);
} else if (file.mozSlice) {
blob = file.mozSlice(block.start, block.end);
}
reader.readAsArrayBuffer(blob);
}
};
buffer_size = 64 * 16 * 1024;
block = {
'file_size' : file.size,
'start' : 0
};
block.end = buffer_size > file.size ? file.size : buffer_size;
worker.addEventListener('message', handle_hash_block, false);
reader = new FileReader();
reader.onload = handle_load_block;
if (file.slice) {
blob = file.slice(block.start, block.end);
} else if (file.webkitSlice) {
blob = file.webkitSlice(block.start, block.end);
} else if (file.mozSlice) {
blob = file.mozSlice(block.start, block.end);
}
reader.readAsArrayBuffer(blob);
private_upload_data[upload_num].hashWorker = worker; //store the worker to make it cancellable
return;
} catch(e) { //some unknown error occurred
}
} //else could not determine file size or could not use the File API's slice() method
} //else the Web Workers API is not supported
}
}
uploadFile(upload_num);
}
/*
* Once a hash is calculated, send the hash along with some callbacks to the hashComplete() callback
*/
function checkHash(upload_num, hash)
{
if (getUploadState(upload_num)!=1) //stop if upload has been cancelled
return;
//because on_hash_complete is likely to run an asynchronous ajax call, pass callbacks to the function in order to take action when ready
var callback_received = false; //only allow one callback to run once
var success_callback = function(data){
if (getUploadState(upload_num)!=1) return false;
if (callback_received) return false;
callback_received = true;
on_progress(upload_num, 100);
on_success(upload_num, data);
return true;
};
var proceed_callback = function(){
if (getUploadState(upload_num)!=1) return false;
if (callback_received) return false;
callback_received = true;
uploadFile(upload_num);
return true;
};
var error_callback = function(error){
if (getUploadState(upload_num)!=1) return false;
if (callback_received) return false;
callback_received = true;
on_error(upload_num, { name: "HashError", message: error });
return true;
};
on_hash_complete.call(upload_contexts[upload_num], hash, { success: success_callback, proceed: proceed_callback, error: error_callback }); //IE has issues with "continue" as property name
}
/*
* Either after validation or a proceed() signal is received from the hash callback, continue to upload the file via AJAX
*/
function uploadFile(upload_num)
{
if (getUploadState(upload_num)!=1) //stop if upload has been cancelled
return;
if (files!=null) //HTML5
{
if (files[upload_num]!=undefined && files[upload_num]!=null)
{
if (window.FormData)
{
var ajax_xhr = $.ajaxSettings.xhr();
if (ajax_xhr.upload) //check if upload property exists in XMLHttpRequest object
{
var file = files[upload_num];
var formData = new FormData();
objectToFormData(formData, request_data);
formData.append(request_file_name, file); //associate the file with options.name, the name of the DOM_file element, or "file" if one does not exist (in that order)
var ajax_settings = { url: ajax_url, data: formData, type: 'post', cache: false, xhrFields: xhrFields, beforeSend: function(jqXHR, settings) {
on_before_send(upload_num, jqXHR, settings);
private_upload_data[upload_num].xhr = jqXHR; //store the jqXHR object to make the upload cancellable
}, xhr: function() { //custom xhr
ajax_xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable)
{
on_progress(upload_num, (e.loaded/e.total)*100);
}
}, false); // for handling the progress of the upload
return ajax_xhr;
}, error: function(xhr) {
private_upload_data[upload_num].xhr = null;
on_error(upload_num, { name: "RequestError", message: "Upload failed", xhr: xhr });
}, success: function(data) {
private_upload_data[upload_num].xhr = null;
on_progress(upload_num, 100);
on_success(upload_num, data);
}, contentType: false, processData: false }; //options to tell JQuery not to process data or worry about content-type
//if expect_type is "auto", let the ajax function determine the type of output based on the mime-type of the response, otherwise force it
if (expect_type!="auto")
{
ajax_settings.dataType = expect_type;
}
$.ajax(ajax_settings); //execute ajax request
return;
}
}
}
else
{
on_error(upload_num, { name: "InternalError", message: "There was an error uploading the file" });
return;
}
}
if (typeof DOM_file=="object" && DOM_file!==null) //FALLBACK TO IFRAME IF BROWSER NOT HTML5 CAPABLE
{
uploadFileFallback(upload_num);
}
else //can't do AJAX file upload, and we weren't given a DOM_file to fall back on (can be caused by a drag-n-drop operation where "files" was given but DOM_file was not)
{
on_error(upload_num, { name: "UnsupportedError", message: "Your browser does not support this upload method" });
}
}
/*
* If the browser does not support AJAX file uploads, fall back to the iframe method
*/
function uploadFileFallback(upload_num)
{
/*
* Limit uploads using the iframe method to 1 for the following reasons:
* 1. To keep it consistent with the one-file-per-request structure
* 2. To prevent confusingly long wait times on individual files because we must wait for all the files to be processed first
*/
if (upload_num==0)
{
var iframe_id = simpleUpload.queueIframe({
origin: getOrigin(ajax_url), //origin of ajax_url, in order to verify potential cross-domain request via postMessage() is secure
expect: expect_type, //expected type of response
complete: function(data){ //on complete
if (getUploadState(upload_num)!=1) //stop if upload has been cancelled
return;
private_upload_data[upload_num].iframe = null;
simpleUpload.dequeueIframe(iframe_id);
on_progress(upload_num, 100);
on_success(upload_num, data);
},
error: function(error){ //on error (since iframes can't catch HTTP status codes, this only happens on parsing error)
if (getUploadState(upload_num)!=1) //stop if upload has been cancelled
return;
private_upload_data[upload_num].iframe = null;
simpleUpload.dequeueIframe(iframe_id);
on_error(upload_num, { name: "RequestError", message: error });
}
});
private_upload_data[upload_num].iframe = iframe_id; //store the iframe id to make the upload cancellable
//hook up hidden form with iframe and include request_data as hidden fields, then submit
var upload_data = objectToInput(request_data);
//add "_iframeUpload" parameter to ajax_url with id to iframe, and "_" parameter with current time in milliseconds to prevent caching
hidden_form.attr("action", ajax_url + ((ajax_url.lastIndexOf("?")==-1) ? "?" : "&") + "_iframeUpload=" + iframe_id + "&_=" + (new Date()).getTime()).attr("target", "simpleUpload_iframe_" + iframe_id).prepend(upload_data).submit();
}
else
{
on_error(upload_num, { name: "UnsupportedError", message: "Multiple file uploads not supported" }); //it is very unlikely this error will ever be returned, if not impossible
}
}
/*
* Convert an object to hidden input fields (must return as string to maintain order)
*/
function objectToInput(obj, parent_node)
{
if (parent_node===undefined || parent_node===null || parent_node==="")
{
parent_node = null;
}
var html = "";
for (var key in obj)
{
if (obj[key]===undefined || obj[key]===null)
{
html += $('<div>').append($('<input type="hidden">').attr("name", (parent_node==null) ? key + "" : parent_node + "[" + key + "]").val("")).html();
}
else if (typeof obj[key]=="object")
{
html += objectToInput(obj[key], (parent_node==null) ? key + "" : parent_node + "[" + key + "]");
}
else if (typeof obj[key]=="boolean")
{
html += $('<div>').append($('<input type="hidden">').attr("name", (parent_node==null) ? key + "" : parent_node + "[" + key + "]").val((obj[key]) ? "true" : "false")).html();
}
else if (typeof obj[key]=="number")
{
html += $('<div>').append($('<input type="hidden">').attr("name", (parent_node==null) ? key + "" : parent_node + "[" + key + "]").val(obj[key] + "")).html();
}
else if (typeof obj[key]=="string")
{
html += $('<div>').append($('<input type="hidden">').attr("name", (parent_node==null) ? key + "" : parent_node + "[" + key + "]").val(obj[key])).html();
}
}
return html;
}