-
Notifications
You must be signed in to change notification settings - Fork 17
/
resumable.js
1322 lines (1265 loc) · 43.1 KB
/
resumable.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
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
/*
* MIT Licensed
* http://www.23developer.com/opensource
* http://github.com/23/resumable.js
* Steffen Tiedemann Christensen, [email protected]
*/
const XMLHttpRequest = require('xhr2').XMLHttpRequest;
(function () {
'use strict'
const Resumable = function (opts) {
if (!(this instanceof Resumable)) {
return new Resumable(opts)
}
this.version = 1.0
// SUPPORTED BY BROWSER?
// Check if these features are support by the browser:
// - File object type
// - Blob object type
// - FileList object type
// - slicing files
this.support = true
if (!this.support) return false
const window = { setTimeout }
// PROPERTIES
const $ = this
$.files = []
$.defaults = {
chunkSize: 1 * 1024 * 1024,
forceChunkSize: false,
simultaneousUploads: 3,
fileParameterName: 'file',
chunkNumberParameterName: 'resumableChunkNumber',
chunkSizeParameterName: 'resumableChunkSize',
currentChunkSizeParameterName: 'resumableCurrentChunkSize',
totalSizeParameterName: 'resumableTotalSize',
typeParameterName: 'resumableType',
identifierParameterName: 'resumableIdentifier',
fileNameParameterName: 'resumableFilename',
relativePathParameterName: 'resumableRelativePath',
totalChunksParameterName: 'resumableTotalChunks',
dragOverClass: 'dragover',
throttleProgressCallbacks: 0.5,
query: {},
headers: {},
preprocess: null,
preprocessFile: null,
method: 'multipart',
uploadMethod: 'POST',
testMethod: 'GET',
prioritizeFirstAndLastChunk: false,
target: '/',
testTarget: null,
parameterNamespace: '',
testChunks: true,
generateUniqueIdentifier: null,
getTarget: null,
maxChunkRetries: 100,
chunkRetryInterval: undefined,
permanentErrors: [400, 401, 403, 404, 409, 415, 500, 501],
maxFiles: undefined,
withCredentials: false,
xhrTimeout: 0,
clearInput: true,
chunkFormat: 'blob',
setChunkTypeFromFile: false,
maxFilesErrorCallback: function (files, errorCount) {
const maxFiles = $.getOpt('maxFiles')
// eslint-disable-next-line no-undef
alert(
'Please upload no more than ' +
maxFiles +
' file' +
(maxFiles === 1 ? '' : 's') +
' at a time.'
)
},
minFileSize: 1,
minFileSizeErrorCallback: function (file, errorCount) {
// eslint-disable-next-line no-undef
alert(
file.fileName ||
file.name +
' is too small, please upload files larger than ' +
$h.formatSize($.getOpt('minFileSize')) +
'.'
)
},
maxFileSize: undefined,
maxFileSizeErrorCallback: function (file, errorCount) {
// eslint-disable-next-line no-undef
alert(
file.fileName ||
file.name +
' is too large, please upload files less than ' +
$h.formatSize($.getOpt('maxFileSize')) +
'.'
)
},
fileType: [],
fileTypeErrorCallback: function (file, errorCount) {
// eslint-disable-next-line no-undef
alert(
file.fileName ||
file.name +
' has type not allowed, please upload files of type ' +
$.getOpt('fileType') +
'.'
)
}
}
$.opts = opts || {}
$.getOpt = function (o) {
let $opt = this
// Get multiple option if passed an array
if (o instanceof Array) {
const options = {}
$h.each(o, function (option) {
options[option] = $opt.getOpt(option)
})
return options
}
// Otherwise, just return a simple option
if ($opt instanceof ResumableChunk) {
if (typeof $opt.opts[o] !== 'undefined') {
return $opt.opts[o]
} else {
$opt = $opt.fileObj
}
}
if ($opt instanceof ResumableFile) {
if (typeof $opt.opts[o] !== 'undefined') {
return $opt.opts[o]
} else {
$opt = $opt.resumableObj
}
}
if ($opt instanceof Resumable) {
if (typeof $opt.opts[o] !== 'undefined') {
return $opt.opts[o]
} else {
return $opt.defaults[o]
}
}
}
$.indexOf = function (array, obj) {
if (array.indexOf) {
return array.indexOf(obj)
}
for (let i = 0; i < array.length; i++) {
if (array[i] === obj) {
return i
}
}
return -1
}
// EVENTS
// catchAll(event, ...)
// fileSuccess(file), fileProgress(file), fileAdded(file, event), filesAdded(files, filesSkipped), fileRetry(file),
// fileError(file, message), complete(), progress(), error(message, file), pause()
$.events = []
$.on = function (event, callback) {
$.events.push(event.toLowerCase(), callback)
}
$.fire = function () {
// `arguments` is an object, not array, in FF, so:
const args = []
for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
// Find event listeners, and support pseudo-event `catchAll`
const event = args[0].toLowerCase()
// eslint-disable-next-line no-redeclare
for (let i = 0; i <= $.events.length; i += 2) {
if ($.events[i] === event) $.events[i + 1].apply($, args.slice(1))
if ($.events[i] === 'catchall') $.events[i + 1].apply(null, args)
}
if (event === 'fileerror') $.fire('error', args[2], args[1])
if (event === 'fileprogress') $.fire('progress')
}
// INTERNAL HELPER METHODS (handy, but ultimately not part of uploading)
const $h = {
stopEvent: function (e) {
e.stopPropagation()
e.preventDefault()
},
each: function (o, callback) {
if (typeof o.length !== 'undefined') {
for (let i = 0; i < o.length; i++) {
// Array or FileList
if (callback(o[i]) === false) return
}
} else {
for (const i in o) {
// Object
if (callback(i, o[i]) === false) return
}
}
},
generateUniqueIdentifier: function (file, event) {
const custom = $.getOpt('generateUniqueIdentifier')
if (typeof custom === 'function') {
return custom(file, event)
}
const relativePath =
file.webkitRelativePath || file.relativePath || file.fileName || file.name // Some confusion in different versions of Firefox
const size = file.size
return size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/gim, '')
},
contains: function (array, test) {
let result = false
$h.each(array, function (value) {
if (value === test) {
result = true
return false
}
return true
})
return result
},
formatSize: function (size) {
if (size < 1024) {
return size + ' bytes'
} else if (size < 1024 * 1024) {
return (size / 1024.0).toFixed(0) + ' KB'
} else if (size < 1024 * 1024 * 1024) {
return (size / 1024.0 / 1024.0).toFixed(1) + ' MB'
} else {
return (size / 1024.0 / 1024.0 / 1024.0).toFixed(1) + ' GB'
}
},
getTarget: function (request, params) {
let target = $.getOpt('target')
if (request === 'test' && $.getOpt('testTarget')) {
target =
$.getOpt('testTarget') === '/'
? $.getOpt('target')
: $.getOpt('testTarget')
}
if (typeof target === 'function') {
return target(params)
}
const separator = target.indexOf('?') < 0 ? '?' : '&'
const joinedParams = params.join('&')
if (joinedParams) target = target + separator + joinedParams
return target
}
}
const onDrop = function (e) {
e.currentTarget.classList.remove($.getOpt('dragOverClass'))
$h.stopEvent(e)
// handle dropped things as items if we can (this lets us deal with folders nicer in some cases)
if (e.dataTransfer && e.dataTransfer.items) {
loadFiles(e.dataTransfer.items, e)
} else if (e.dataTransfer && e.dataTransfer.files) {
// else handle them as files
loadFiles(e.dataTransfer.files, e)
}
}
const onDragLeave = function (e) {
e.currentTarget.classList.remove($.getOpt('dragOverClass'))
}
const onDragOverEnter = function (e) {
e.preventDefault()
const dt = e.dataTransfer
if ($.indexOf(dt.types, 'Files') >= 0) {
// only for file drop
e.stopPropagation()
dt.dropEffect = 'copy'
dt.effectAllowed = 'copy'
e.currentTarget.classList.add($.getOpt('dragOverClass'))
} else {
// not work on IE/Edge....
dt.dropEffect = 'none'
dt.effectAllowed = 'none'
}
}
/**
* processes a single upload item (file or directory)
* @param {Object} item item to upload, may be file or directory entry
* @param {string} path current file path
* @param {File[]} items list of files to append new items to
* @param {Function} cb callback invoked when item is processed
*/
function processItem (item, path, items, cb) {
let entry
if (item.isFile) {
// file provided
return item.file(function (file) {
file.relativePath = path + file.name
items.push(file)
cb()
})
} else if (item.isDirectory) {
// item is already a directory entry, just assign
entry = item
// eslint-disable-next-line no-undef
} else if (item instanceof File) {
items.push(item)
}
if (typeof item.webkitGetAsEntry === 'function') {
// get entry from file object
entry = item.webkitGetAsEntry()
}
if (entry && entry.isDirectory) {
// directory provided, process it
return processDirectory(entry, path + entry.name + '/', items, cb)
}
if (typeof item.getAsFile === 'function') {
// item represents a File object, convert it
item = item.getAsFile()
// eslint-disable-next-line no-undef
if (item instanceof File) {
item.relativePath = path + item.name
items.push(item)
}
}
cb() // indicate processing is done
}
/**
* cps-style list iteration.
* invokes all functions in list and waits for their callback to be
* triggered.
* @param {Function[]} items list of functions expecting callback parameter
* @param {Function} cb callback to trigger after the last callback has been invoked
*/
function processCallbacks (items, cb) {
if (!items || items.length === 0) {
// empty or no list, invoke callback
return cb()
}
// invoke current function, pass the next part as continuation
items[0](function () {
processCallbacks(items.slice(1), cb)
})
}
/**
* recursively traverse directory and collect files to upload
* @param {Object} directory directory to process
* @param {string} path current path
* @param {File[]} items target list of items
* @param {Function} cb callback invoked after traversing directory
*/
function processDirectory (directory, path, items, cb) {
const dirReader = directory.createReader()
let allEntries = []
function readEntries () {
dirReader.readEntries(function (entries) {
if (entries.length) {
allEntries = allEntries.concat(entries)
return readEntries()
}
// process all conversion callbacks, finally invoke own one
processCallbacks(
allEntries.map(function (entry) {
// bind all properties except for callback
return processItem.bind(null, entry, path, items)
}),
cb
)
})
}
readEntries()
}
/**
* process items to extract files to be uploaded
* @param {File[]} items items to process
* @param {Event} event event that led to upload
*/
function loadFiles (items, event) {
if (!items.length) {
return // nothing to do
}
$.fire('beforeAdd')
const files = []
processCallbacks(
Array.prototype.map.call(items, function (item) {
// bind all properties except for callback
let entry = item
if (typeof item.webkitGetAsEntry === 'function') {
entry = item.webkitGetAsEntry()
}
return processItem.bind(null, entry, '', files)
}),
function () {
if (files.length) {
// at least one file found
appendFilesFromFileList(files, event)
}
}
)
}
const appendFilesFromFileList = function (fileList, event) {
// check for uploading too many files
let errorCount = 0
const o = $.getOpt([
'maxFiles',
'minFileSize',
'maxFileSize',
'maxFilesErrorCallback',
'minFileSizeErrorCallback',
'maxFileSizeErrorCallback',
'fileType',
'fileTypeErrorCallback'
])
if (
typeof o.maxFiles !== 'undefined' &&
o.maxFiles < fileList.length + $.files.length
) {
// if single-file upload, file is already added, and trying to add 1 new file, simply replace the already-added file
if (o.maxFiles === 1 && $.files.length === 1 && fileList.length === 1) {
$.removeFile($.files[0])
} else {
o.maxFilesErrorCallback(fileList, errorCount++)
return false
}
}
const files = []
const filesSkipped = []
let remaining = fileList.length
const decreaseReamining = function () {
if (!--remaining) {
// all files processed, trigger event
if (!files.length && !filesSkipped.length) {
// no succeeded files, just skip
return
}
window.setTimeout(function () {
$.fire('filesAdded', files, filesSkipped)
}, 0)
}
}
$h.each(fileList, function (file) {
const fileName = file.name
const fileType = file.type // e.g video/mp4
if (o.fileType.length > 0) {
let fileTypeFound = false
for (const index in o.fileType) {
// For good behaviour we do some inital sanitizing. Remove spaces and lowercase all
o.fileType[index] = o.fileType[index].replace(/\s/g, '').toLowerCase()
// Allowing for both [extension, .extension, mime/type, mime/*]
const extension =
(o.fileType[index].match(/^[^.][^/]+$/) ? '.' : '') + o.fileType[index]
if (
fileName.substr(-1 * extension.length).toLowerCase() === extension ||
// If MIME type, check for wildcard or if extension matches the files tiletype
(extension.indexOf('/') !== -1 &&
((extension.indexOf('*') !== -1 &&
fileType.substr(0, extension.indexOf('*')) ===
extension.substr(0, extension.indexOf('*'))) ||
fileType === extension))
) {
fileTypeFound = true
break
}
}
if (!fileTypeFound) {
o.fileTypeErrorCallback(file, errorCount++)
return true
}
}
if (typeof o.minFileSize !== 'undefined' && file.size < o.minFileSize) {
o.minFileSizeErrorCallback(file, errorCount++)
return true
}
if (typeof o.maxFileSize !== 'undefined' && file.size > o.maxFileSize) {
o.maxFileSizeErrorCallback(file, errorCount++)
return true
}
function addFile (uniqueIdentifier) {
if (!$.getFromUniqueIdentifier(uniqueIdentifier)) {
(function () {
file.uniqueIdentifier = uniqueIdentifier
const f = new ResumableFile($, file, uniqueIdentifier)
$.files.push(f)
files.push(f)
f.container = typeof event !== 'undefined' ? event.srcElement : null
window.setTimeout(function () {
$.fire('fileAdded', f, event)
}, 0)
})()
} else {
filesSkipped.push(file)
}
decreaseReamining()
}
// directories have size == 0
const uniqueIdentifier = $h.generateUniqueIdentifier(file, event)
if (uniqueIdentifier && typeof uniqueIdentifier.then === 'function') {
// Promise or Promise-like object provided as unique identifier
uniqueIdentifier.then(
function (uniqueIdentifier) {
// unique identifier generation succeeded
addFile(uniqueIdentifier)
},
function () {
// unique identifier generation failed
// skip further processing, only decrease file count
decreaseReamining()
}
)
} else {
// non-Promise provided as unique identifier, process synchronously
addFile(uniqueIdentifier)
}
})
}
// INTERNAL OBJECT TYPES
function ResumableFile (resumableObj, file, uniqueIdentifier) {
const $ = this
$.opts = {}
$.getOpt = resumableObj.getOpt
$._prevProgress = 0
$.resumableObj = resumableObj
$.file = file
$.fileName = file.fileName || file.name // Some confusion in different versions of Firefox
$.size = file.size
$.relativePath = file.relativePath || file.webkitRelativePath || $.fileName
$.uniqueIdentifier = uniqueIdentifier
$._pause = false
$.container = ''
$.preprocessState = 0 // 0 = unprocessed, 1 = processing, 2 = finished
let _error = uniqueIdentifier !== undefined
// Callback when something happens within the chunk
const chunkEvent = function (event, message) {
// event can be 'progress', 'success', 'error' or 'retry'
switch (event) {
case 'progress':
$.resumableObj.fire('fileProgress', $, message)
break
case 'error':
$.abort()
_error = true
$.chunks = []
$.resumableObj.fire('fileError', $, message)
break
case 'success':
if (_error) return
$.resumableObj.fire('fileProgress', $, message) // it's at least progress
if ($.isComplete()) {
$.resumableObj.fire('fileSuccess', $, message)
}
break
case 'retry':
$.resumableObj.fire('fileRetry', $)
break
}
}
// Main code to set up a file object with chunks,
// packaged to be able to handle retries if needed.
$.chunks = []
$.abort = function () {
// Stop current uploads
let abortCount = 0
$h.each($.chunks, function (c) {
if (c.status() === 'uploading') {
c.abort()
abortCount++
}
})
if (abortCount > 0) $.resumableObj.fire('fileProgress', $)
}
$.cancel = function () {
// Reset this file to be void
const _chunks = $.chunks
$.chunks = []
// Stop current uploads
$h.each(_chunks, function (c) {
if (c.status() === 'uploading') {
c.abort()
$.resumableObj.uploadNextChunk()
}
})
$.resumableObj.removeFile($)
$.resumableObj.fire('fileProgress', $)
}
$.retry = function () {
$.bootstrap()
let firedRetry = false
$.resumableObj.on('chunkingComplete', function () {
if (!firedRetry) $.resumableObj.upload()
firedRetry = true
})
}
$.bootstrap = function () {
$.abort()
_error = false
// Rebuild stack of chunks from file
$.chunks = []
$._prevProgress = 0
const round = $.getOpt('forceChunkSize') ? Math.ceil : Math.floor
const maxOffset = Math.max(round($.file.size / $.getOpt('chunkSize')), 1)
for (let offset = 0; offset < maxOffset; offset++) {
(function (offset) {
window.setTimeout(function () {
$.chunks.push(
new ResumableChunk($.resumableObj, $, offset, chunkEvent)
)
$.resumableObj.fire('chunkingProgress', $, offset / maxOffset)
}, 0)
})(offset)
}
window.setTimeout(function () {
$.resumableObj.fire('chunkingComplete', $)
}, 0)
}
$.progress = function () {
if (_error) return 1
// Sum up progress across everything
let ret = 0
let error = false
$h.each($.chunks, function (c) {
if (c.status() === 'error') error = true
ret += c.progress(true) // get chunk progress relative to entire file
})
ret = error ? 1 : ret > 0.99999 ? 1 : ret
ret = Math.max($._prevProgress, ret) // We don't want to lose percentages when an upload is paused
$._prevProgress = ret
return ret
}
$.isUploading = function () {
let uploading = false
$h.each($.chunks, function (chunk) {
if (chunk.status() === 'uploading') {
uploading = true
return false
}
})
return uploading
}
$.isComplete = function () {
let outstanding = false
if ($.preprocessState === 1) {
return false
}
$h.each($.chunks, function (chunk) {
const status = chunk.status()
if (
status === 'pending' ||
status === 'uploading' ||
chunk.preprocessState === 1
) {
outstanding = true
return false
}
})
return !outstanding
}
$.pause = function (pause) {
if (typeof pause === 'undefined') {
$._pause = !$._pause
} else {
$._pause = pause
}
}
$.isPaused = function () {
return $._pause
}
$.preprocessFinished = function () {
$.preprocessState = 2
$.upload()
}
$.upload = function () {
let found = false
if ($.isPaused() === false) {
const preprocess = $.getOpt('preprocessFile')
if (typeof preprocess === 'function') {
switch ($.preprocessState) {
case 0:
$.preprocessState = 1
preprocess($)
return true
case 1:
return true
case 2:
break
}
}
$h.each($.chunks, function (chunk) {
if (chunk.status() === 'pending' && chunk.preprocessState !== 1) {
chunk.send()
found = true
return false
}
})
}
return found
}
$.markChunksCompleted = function (chunkNumber) {
if (!$.chunks || $.chunks.length <= chunkNumber) {
return
}
for (let num = 0; num < chunkNumber; num++) {
$.chunks[num].markComplete = true
}
}
// Bootstrap and return
$.resumableObj.fire('chunkingStart', $)
$.bootstrap()
return this
}
function ResumableChunk (resumableObj, fileObj, offset, callback) {
const $ = this
$.opts = {}
$.getOpt = resumableObj.getOpt
$.resumableObj = resumableObj
$.fileObj = fileObj
$.fileObjSize = fileObj.size
$.fileObjType = fileObj.file.type
$.offset = offset
$.callback = callback
$.lastProgressCallback = new Date()
$.tested = false
$.retries = 0
$.pendingRetry = false
$.preprocessState = 0 // 0 = unprocessed, 1 = processing, 2 = finished
$.markComplete = false
// Computed properties
const chunkSize = $.getOpt('chunkSize')
$.loaded = 0
$.startByte = $.offset * chunkSize
$.endByte = Math.min($.fileObjSize, (($.offset + 1) * chunkSize) - 1)
if ($.fileObjSize - $.endByte < chunkSize && !$.getOpt('forceChunkSize')) {
// The last chunk will be bigger than the chunk size, but less than 2*chunkSize
$.endByte = $.fileObjSize
}
$.xhr = null
// test() makes a GET request without any data to see if the chunk has already been uploaded in a previous session
$.test = function () {
// Set up request and listen for event
$.xhr = new XMLHttpRequest()
const testHandler = function (e) {
$.tested = true
const status = $.status()
if (status === 'success') {
$.callback(status, $.message())
$.resumableObj.uploadNextChunk()
} else {
$.send()
}
}
$.xhr.addEventListener('load', testHandler, false)
$.xhr.addEventListener('error', testHandler, false)
$.xhr.addEventListener('timeout', testHandler, false)
// Add data from the query options
let params = []
const parameterNamespace = $.getOpt('parameterNamespace')
let customQuery = $.getOpt('query')
if (typeof customQuery === 'function') customQuery = customQuery($.fileObj, $)
$h.each(customQuery, function (k, v) {
params.push(
[encodeURIComponent(parameterNamespace + k), encodeURIComponent(v)].join(
'='
)
)
})
// Add extra data to identify chunk
params = params.concat(
[
// define key/value pairs for additional parameters
['chunkNumberParameterName', $.offset + 1],
['chunkSizeParameterName', $.getOpt('chunkSize')],
['currentChunkSizeParameterName', $.endByte - $.startByte],
['totalSizeParameterName', $.fileObjSize],
['typeParameterName', $.fileObjType],
['identifierParameterName', $.fileObj.uniqueIdentifier],
['fileNameParameterName', $.fileObj.fileName],
['relativePathParameterName', $.fileObj.relativePath],
['totalChunksParameterName', $.fileObj.chunks.length]
]
.filter(function (pair) {
// include items that resolve to truthy values
// i.e. exclude false, null, undefined and empty strings
return $.getOpt(pair[0])
})
.map(function (pair) {
// map each key/value pair to its final form
return [
parameterNamespace + $.getOpt(pair[0]),
encodeURIComponent(pair[1])
].join('=')
})
)
// Append the relevant chunk and send it
$.xhr.open($.getOpt('testMethod'), $h.getTarget('test', params))
$.xhr.timeout = $.getOpt('xhrTimeout')
$.xhr.withCredentials = $.getOpt('withCredentials')
// Add data from header options
let customHeaders = $.getOpt('headers')
if (typeof customHeaders === 'function') {
customHeaders = customHeaders($.fileObj, $)
}
$h.each(customHeaders, function (k, v) {
$.xhr.setRequestHeader(k, v)
})
$.xhr.send(null)
}
$.preprocessFinished = function () {
$.preprocessState = 2
$.send()
}
// send() uploads the actual data in a POST call
$.send = function () {
const preprocess = $.getOpt('preprocess')
if (typeof preprocess === 'function') {
switch ($.preprocessState) {
case 0:
$.preprocessState = 1
preprocess($)
return
case 1:
return
case 2:
break
}
}
if ($.getOpt('testChunks') && !$.tested) {
$.test()
return
}
// Set up request and listen for event
$.xhr = new XMLHttpRequest()
// Progress
$.xhr.upload.addEventListener(
'progress',
function (e) {
if (
new Date() - $.lastProgressCallback >
$.getOpt('throttleProgressCallbacks') * 1000
) {
$.callback('progress')
$.lastProgressCallback = new Date()
}
$.loaded = e.loaded || 0
},
false
)
$.loaded = 0
$.pendingRetry = false
$.callback('progress')
// Done (either done, failed or retry)
const doneHandler = function (e) {
const status = $.status()
if (status === 'success' || status === 'error') {
$.callback(status, $.message())
$.resumableObj.uploadNextChunk()
} else {
$.callback('retry', $.message())
$.abort()
$.retries++
const retryInterval = $.getOpt('chunkRetryInterval')
if (retryInterval !== undefined) {
$.pendingRetry = true
setTimeout($.send, retryInterval)
} else {
$.send()
}
}
}
$.xhr.addEventListener('load', doneHandler, false)
$.xhr.addEventListener('error', doneHandler, false)
$.xhr.addEventListener('timeout', doneHandler, false)
// Set up the basic query data from Resumable
const query = [
['chunkNumberParameterName', $.offset + 1],
['chunkSizeParameterName', $.getOpt('chunkSize')],
['currentChunkSizeParameterName', $.endByte - $.startByte],
['totalSizeParameterName', $.fileObjSize],
['typeParameterName', $.fileObjType],
['identifierParameterName', $.fileObj.uniqueIdentifier],
['fileNameParameterName', $.fileObj.fileName],
['relativePathParameterName', $.fileObj.relativePath],
['totalChunksParameterName', $.fileObj.chunks.length]
]
.filter(function (pair) {
// include items that resolve to truthy values
// i.e. exclude false, null, undefined and empty strings
return $.getOpt(pair[0])
})
.reduce(function (query, pair) {
// assign query key/value
query[$.getOpt(pair[0])] = pair[1]
return query
}, {})
// Mix in custom data
let customQuery = $.getOpt('query')
if (typeof customQuery === 'function') customQuery = customQuery($.fileObj, $)
$h.each(customQuery, function (k, v) {
query[k] = v
})
const func = $.fileObj.file.slice
? 'slice'
: $.fileObj.file.mozSlice
? 'mozSlice'
: $.fileObj.file.webkitSlice
? 'webkitSlice'
: 'slice'
const bytes = $.fileObj.file[func](
$.startByte,
$.endByte,
$.getOpt('setChunkTypeFromFile') ? $.fileObj.file.type : ''
)
let data = null
const params = []
const parameterNamespace = $.getOpt('parameterNamespace')
if ($.getOpt('method') === 'octet') {
// Add data from the query options
data = bytes
$h.each(query, function (k, v) {
params.push(
[
encodeURIComponent(parameterNamespace + k),
encodeURIComponent(v)
].join('=')
)
})
} else {
// Add data from the query options
data = new FormData()
$h.each(query, function (k, v) {
data.append(parameterNamespace + k, v)
params.push(
[
encodeURIComponent(parameterNamespace + k),
encodeURIComponent(v)
].join('=')
)
})
if ($.getOpt('chunkFormat') === 'blob') {
data.append(
parameterNamespace + $.getOpt('fileParameterName'),
bytes,
$.fileObj.fileName
)
} else if ($.getOpt('chunkFormat') === 'base64') {
// eslint-disable-next-line no-undef
const fr = new FileReader()
fr.onload = function (e) {
data.append(
parameterNamespace + $.getOpt('fileParameterName'),
fr.result
)
$.xhr.send(data)
}
fr.readAsDataURL(bytes)
}
}
const target = $h.getTarget('upload', params)
const method = $.getOpt('uploadMethod')
$.xhr.open(method, target)
if ($.getOpt('method') === 'octet') {
$.xhr.setRequestHeader('Content-Type', 'application/octet-stream')
}
$.xhr.timeout = $.getOpt('xhrTimeout')
$.xhr.withCredentials = $.getOpt('withCredentials')
// Add data from header options
let customHeaders = $.getOpt('headers')