forked from moxiecode/plupload
/
plupload.html5.js
1415 lines (1144 loc) · 41.7 KB
/
plupload.html5.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
/**
* plupload.html5.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
// JSLint defined globals
/*global plupload:false, File:false, window:false, atob:false, FormData:false, FileReader:false, ArrayBuffer:false, Uint8Array:false, BlobBuilder:false, unescape:false */
(function(window, document, plupload, undef) {
var html5files = {}, // queue of original File objects
fakeSafariDragDrop;
function readFileAsDataURL(file, callback) {
var reader;
// Use FileReader if it's available
if ("FileReader" in window) {
reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
callback(reader.result);
};
} else {
return callback(file.getAsDataURL());
}
}
function readFileAsBinary(file, callback) {
var reader;
// Use FileReader if it's available
if ("FileReader" in window) {
reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
callback(reader.result);
};
} else {
return callback(file.getAsBinary());
}
}
function scaleImage(file, resize, mime, callback) {
var canvas, context, img, scale,
up = this;
readFileAsDataURL(html5files[file.id], function(data) {
// Setup canvas and context
canvas = document.createElement("canvas");
canvas.style.display = 'none';
document.body.appendChild(canvas);
context = canvas.getContext('2d');
// Load image
img = new Image();
img.onerror = img.onabort = function() {
// Failed to load, the image may be invalid
callback({success : false});
};
img.onload = function() {
var width, height, percentage, jpegHeaders, exifParser;
if (!resize['width']) {
resize['width'] = img.width;
}
if (!resize['height']) {
resize['height'] = img.height;
}
scale = Math.min(resize.width / img.width, resize.height / img.height);
if (scale < 1 || (scale === 1 && mime === 'image/jpeg')) {
width = Math.round(img.width * scale);
height = Math.round(img.height * scale);
// Scale image and canvas
canvas.width = width;
canvas.height = height;
context.drawImage(img, 0, 0, width, height);
// Preserve JPEG headers
if (mime === 'image/jpeg') {
jpegHeaders = new JPEG_Headers(atob(data.substring(data.indexOf('base64,') + 7)));
if (jpegHeaders['headers'] && jpegHeaders['headers'].length) {
exifParser = new ExifParser();
if (exifParser.init(jpegHeaders.get('exif')[0])) {
// Set new width and height
exifParser.setExif('PixelXDimension', width);
exifParser.setExif('PixelYDimension', height);
// Update EXIF header
jpegHeaders.set('exif', exifParser.getBinary());
// trigger Exif events only if someone listens to them
if (up.hasEventListener('ExifData')) {
up.trigger('ExifData', file, exifParser.EXIF());
}
if (up.hasEventListener('GpsData')) {
up.trigger('GpsData', file, exifParser.GPS());
}
}
}
if (resize['quality']) {
// Try quality property first
try {
data = canvas.toDataURL(mime, resize['quality'] / 100);
} catch (e) {
data = canvas.toDataURL(mime);
}
}
} else {
data = canvas.toDataURL(mime);
}
// Remove data prefix information and grab the base64 encoded data and decode it
data = data.substring(data.indexOf('base64,') + 7);
data = atob(data);
// Restore JPEG headers if applicable
if (jpegHeaders && jpegHeaders['headers'] && jpegHeaders['headers'].length) {
data = jpegHeaders.restore(data);
jpegHeaders.purge(); // free memory
}
// Remove canvas and execute callback with decoded image data
canvas.parentNode.removeChild(canvas);
callback({success : true, data : data});
} else {
// Image does not need to be resized
callback({success : false});
}
};
img.src = data;
});
}
/**
* HMTL5 implementation. This runtime supports these features: dragdrop, jpgresize, pngresize.
*
* @static
* @class plupload.runtimes.Html5
* @extends plupload.Runtime
*/
plupload.runtimes.Html5 = plupload.addRuntime("html5", {
/**
* Returns a list of supported features for the runtime.
*
* @return {Object} Name/value object with supported features.
*/
getFeatures : function() {
var xhr, hasXhrSupport, hasProgress, canSendBinary, dataAccessSupport, sliceSupport;
hasXhrSupport = hasProgress = dataAccessSupport = sliceSupport = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
hasProgress = !!xhr.upload;
hasXhrSupport = !!(xhr.sendAsBinary || xhr.upload);
}
// Check for support for various features
if (hasXhrSupport) {
canSendBinary = !!(xhr.sendAsBinary || (window.Uint8Array && window.ArrayBuffer));
// Set dataAccessSupport only for Gecko since BlobBuilder and XHR doesn't handle binary data correctly
dataAccessSupport = !!(File && (File.prototype.getAsDataURL || window.FileReader) && canSendBinary);
sliceSupport = !!(File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice));
}
// sniff out Safari for Windows and fake drag/drop
fakeSafariDragDrop = plupload.ua.safari && plupload.ua.windows;
return {
html5: hasXhrSupport, // This is a special one that we check inside the init call
dragdrop: (function() {
// this comes directly from Modernizr: http://www.modernizr.com/
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
}()),
jpgresize: dataAccessSupport,
pngresize: dataAccessSupport,
multipart: dataAccessSupport || !!window.FileReader || !!window.FormData,
canSendBinary: canSendBinary,
// gecko 2/5/6 can't send blob with FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150
cantSendBlobInFormData: !!(plupload.ua.gecko && window.FormData && window.FileReader && !FileReader.prototype.readAsArrayBuffer),
progress: hasProgress,
chunks: sliceSupport,
// Safari on Windows has problems when selecting multiple files
multi_selection: !(plupload.ua.safari && plupload.ua.windows),
// WebKit and Gecko 2+ can trigger file dialog progrmmatically
triggerDialog: (plupload.ua.gecko && window.FormData || plupload.ua.webkit)
};
},
/**
* Initializes the upload runtime.
*
* @method init
* @param {plupload.Uploader} uploader Uploader instance that needs to be initialized.
* @param {function} callback Callback to execute when the runtime initializes or fails to initialize. If it succeeds an object with a parameter name success will be set to true.
*/
init : function(uploader, callback) {
var features;
function hasFiles(dataTransfer) {
if (!dataTransfer || typeof(dataTransfer.files) === "undefined") {
return false;
}
var types = plupload.toArray(dataTransfer.types || []);
return types.indexOf("public.file-url") !== -1 || // Safari < 5
types.indexOf("application/x-moz-file") !== -1 || // Gecko < 1.9.2 (< Firefox 3.6)
types.indexOf("Files") !== -1 || // Standard
types.length === 0;
}
function addSelectedFiles(native_files) {
var file, i, files = [], id, fileNames = {};
// Add the selected files to the file queue
for (i = 0; i < native_files.length; i++) {
file = native_files[i];
// Safari on Windows will add first file from dragged set multiple times
// @see: https://bugs.webkit.org/show_bug.cgi?id=37957
if (fileNames[file.name]) {
continue;
}
fileNames[file.name] = true;
// Store away gears blob internally
id = plupload.guid();
html5files[id] = file;
// Expose id, name and size
files.push(new plupload.File(id, file.fileName || file.name, file.fileSize || file.size)); // fileName / fileSize depricated
}
// Trigger FilesAdded event if we added any
if (files.length) {
uploader.trigger("FilesAdded", files);
}
}
// No HTML5 upload support
features = this.getFeatures();
if (!features.html5) {
callback({success : false});
return;
}
uploader.bind("Init", function(up) {
var inputContainer, browseButton, mimes = [], i, y, filters = up.settings.filters, ext, type, container = document.body, inputFile;
// Create input container and insert it at an absolute position within the browse button
inputContainer = document.createElement('div');
inputContainer.id = up.id + '_html5_container';
plupload.extend(inputContainer.style, {
position : 'absolute',
background : uploader.settings.shim_bgcolor || 'transparent',
width : '100px',
height : '100px',
overflow : 'hidden',
zIndex : 99999,
opacity : uploader.settings.shim_bgcolor ? '' : 0 // Force transparent if bgcolor is undefined
});
inputContainer.className = 'plupload html5';
if (uploader.settings.container) {
container = document.getElementById(uploader.settings.container);
if (plupload.getStyle(container, 'position') === 'static') {
container.style.position = 'relative';
}
}
container.appendChild(inputContainer);
// Convert extensions to mime types list
no_type_restriction:
for (i = 0; i < filters.length; i++) {
ext = filters[i].extensions.split(/,/);
for (y = 0; y < ext.length; y++) {
// If there's an asterisk in the list, then accept attribute is not required
if (ext[y] === '*') {
mimes = [];
break no_type_restriction;
}
type = plupload.mimeTypes[ext[y]];
if (type) {
mimes.push(type);
}
}
}
// Insert the input inside the input container
inputContainer.innerHTML = '<input id="' + uploader.id + '_html5" ' + ' style="font-size:999px"' +
' type="file" accept="' + mimes.join(',') + '" ' +
(uploader.settings.multi_selection && uploader.features.multi_selection ? 'multiple="multiple"' : '') + ' />';
inputContainer.scrollTop = 100;
inputFile = document.getElementById(uploader.id + '_html5');
if (up.features.triggerDialog) {
plupload.extend(inputFile.style, {
position: 'absolute',
width: '100%',
height: '100%'
});
} else {
// shows arrow cursor instead of the text one, bit more logical
plupload.extend(inputFile.style, {
cssFloat: 'right',
styleFloat: 'right'
});
}
inputFile.onchange = function() {
// Add the selected files from file input
addSelectedFiles(this.files);
// Clearing the value enables the user to select the same file again if they want to
this.value = '';
};
/* Since we have to place input[type=file] on top of the browse_button for some browsers (FF, Opera),
browse_button loses interactivity, here we try to neutralize this issue highlighting browse_button
with a special classes
TODO: needs to be revised as things will change */
browseButton = document.getElementById(up.settings.browse_button);
if (browseButton) {
var hoverClass = up.settings.browse_button_hover,
activeClass = up.settings.browse_button_active,
topElement = up.features.triggerDialog ? browseButton : inputContainer;
if (hoverClass) {
plupload.addEvent(topElement, 'mouseover', function() {
plupload.addClass(browseButton, hoverClass);
}, up.id);
plupload.addEvent(topElement, 'mouseout', function() {
plupload.removeClass(browseButton, hoverClass);
}, up.id);
}
if (activeClass) {
plupload.addEvent(topElement, 'mousedown', function() {
plupload.addClass(browseButton, activeClass);
}, up.id);
plupload.addEvent(document.body, 'mouseup', function() {
plupload.removeClass(browseButton, activeClass);
}, up.id);
}
// Route click event to the input[type=file] element for supporting browsers
if (up.features.triggerDialog) {
plupload.addEvent(browseButton, 'click', function(e) {
document.getElementById(up.id + '_html5').click();
e.preventDefault();
}, up.id);
}
}
});
// Add drop handler
uploader.bind("PostInit", function() {
var dropElm = document.getElementById(uploader.settings.drop_element);
if (dropElm) {
// Lets fake drag/drop on Safari by moving a input type file in front of the mouse pointer when we drag into the drop zone
// TODO: Remove this logic once Safari has official drag/drop support
if (fakeSafariDragDrop) {
plupload.addEvent(dropElm, 'dragenter', function(e) {
var dropInputElm, dropPos, dropSize;
// Get or create drop zone
dropInputElm = document.getElementById(uploader.id + "_drop");
if (!dropInputElm && hasFiles(e.dataTransfer)) {
dropInputElm = document.createElement("input");
dropInputElm.setAttribute('type', "file");
dropInputElm.setAttribute('id', uploader.id + "_drop");
dropInputElm.setAttribute('multiple', 'multiple');
plupload.addEvent(dropInputElm, 'change', function() {
// Add the selected files from file input
addSelectedFiles(this.files);
// Remove input element
plupload.removeEvent(dropInputElm, 'change', uploader.id);
dropInputElm.parentNode.removeChild(dropInputElm);
}, uploader.id);
dropElm.appendChild(dropInputElm);
}
dropPos = plupload.getPos(dropElm, document.getElementById(uploader.settings.container));
dropSize = plupload.getSize(dropElm);
if (plupload.getStyle(dropElm, 'position') === 'static') {
plupload.extend(dropElm.style, {
position : 'relative'
});
}
plupload.extend(dropInputElm.style, {
position : 'absolute',
display : 'block',
top : 0,
left : 0,
width : dropSize.w + 'px',
height : dropSize.h + 'px',
opacity : 0
});
}, uploader.id);
return;
}
// Block browser default drag over
plupload.addEvent(dropElm, 'dragover', function(e) {
if (hasFiles(e.dataTransfer)) {
e.preventDefault();
}
}, uploader.id);
// Attach drop handler and grab files
plupload.addEvent(dropElm, 'drop', function(e) {
var dataTransfer = e.dataTransfer;
if (!hasFiles(dataTransfer)) {
return;
}
// Add dropped files
addSelectedFiles(dataTransfer.files);
e.preventDefault();
}, uploader.id);
}
});
uploader.bind("Refresh", function(up) {
var browseButton, browsePos, browseSize, inputContainer, zIndex;
browseButton = document.getElementById(uploader.settings.browse_button);
if (browseButton) {
browsePos = plupload.getPos(browseButton, document.getElementById(up.settings.container));
browseSize = plupload.getSize(browseButton);
inputContainer = document.getElementById(uploader.id + '_html5_container');
plupload.extend(inputContainer.style, {
top : browsePos.y + 'px',
left : browsePos.x + 'px',
width : browseSize.w + 'px',
height : browseSize.h + 'px'
});
// for WebKit place input element underneath the browse button and route onclick event
// TODO: revise when browser support for this feature will change
if (uploader.features.triggerDialog) {
if (plupload.getStyle(browseButton, 'position') === 'static') {
plupload.extend(browseButton.style, {
position : 'relative'
});
}
zIndex = parseInt(plupload.getStyle(browseButton, 'z-index'), 10);
if (isNaN(zIndex)) {
zIndex = 0;
}
plupload.extend(browseButton.style, {
zIndex : zIndex
});
plupload.extend(inputContainer.style, {
zIndex : zIndex - 1
});
}
}
});
uploader.bind("UploadFile", function(up, file) {
var settings = up.settings, nativeFile, resize;
function w3cBlobSlice(blob, start, end) {
var blobSlice;
if (File.prototype.slice) {
try {
blob.slice(); // depricated version will throw WRONG_ARGUMENTS_ERR exception
return blob.slice(start, end);
} catch (e) {
// depricated slice method
return blob.slice(start, end - start);
}
// slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672
} else if (blobSlice = File.prototype.webkitSlice || File.prototype.mozSlice) {
return blobSlice.call(blob, start, end);
} else {
return null; // or throw some exception
}
}
function sendBinaryBlob(blob) {
var chunk = 0, loaded = 0,
fr = ("FileReader" in window) ? new FileReader : null;
function uploadNextChunk() {
var chunkBlob, br, chunks, args, chunkSize, curChunkSize, mimeType, url = up.settings.url;
function prepareAndSend(bin) {
var multipartDeltaSize = 0,
xhr = new XMLHttpRequest,
upload = xhr.upload,
boundary = '----pluploadboundary' + plupload.guid(), formData, dashdash = '--', crlf = '\r\n', multipartBlob = ''
// Do we have upload progress support
if (upload) {
upload.onprogress = function(e) {
file.loaded = Math.min(file.size, loaded + e.loaded - multipartDeltaSize); // Loaded can be larger than file size due to multipart encoding
up.trigger('UploadProgress', file);
};
}
xhr.onreadystatechange = function() {
var httpStatus, chunkArgs;
if (xhr.readyState == 4) {
// Getting the HTTP status might fail on some Gecko versions
try {
httpStatus = xhr.status;
} catch (ex) {
httpStatus = 0;
}
// Is error status
if (httpStatus >= 400) {
up.trigger('Error', {
code : plupload.HTTP_ERROR,
message : plupload.translate('HTTP Error.'),
file : file,
status : httpStatus
});
} else {
// Handle chunk response
if (chunks) {
chunkArgs = {
chunk : chunk,
chunks : chunks,
response : xhr.responseText,
status : httpStatus
};
up.trigger('ChunkUploaded', file, chunkArgs);
loaded += curChunkSize;
// Stop upload
if (chunkArgs.cancelled) {
file.status = plupload.FAILED;
return;
}
file.loaded = Math.min(file.size, (chunk + 1) * chunkSize);
} else {
file.loaded = file.size;
}
up.trigger('UploadProgress', file);
bin = chunkBlob = formData = multipartBlob = null; // Free memory
// Check if file is uploaded
if (!chunks || ++chunk >= chunks) {
file.status = plupload.DONE;
up.trigger('FileUploaded', file, {
response : xhr.responseText,
status : httpStatus
});
} else {
// Still chunks left
uploadNextChunk();
}
}
xhr = null;
}
};
// Build multipart request
if (up.settings.multipart && features.multipart) {
args.name = file.target_name || file.name;
xhr.open("post", url, true);
// Set custom headers
plupload.each(up.settings.headers, function(value, name) {
xhr.setRequestHeader(name, value);
});
// if has FormData support like Chrome 6+, Safari 5+, Firefox 4, use it
if (typeof(bin) !== 'string' && !!window.FormData) {
formData = new FormData();
// Add multipart params
plupload.each(plupload.extend(args, up.settings.multipart_params), function(value, name) {
formData.append(name, value);
});
// Add file and send it
formData.append(up.settings.file_data_name, bin);
xhr.send(formData);
return;
} // if no FormData we can still try to send it directly as last resort (see below)
if (typeof(bin) === 'string') {
// Trying to send the whole thing as binary...
// multipart request
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// append multipart parameters
plupload.each(plupload.extend(args, up.settings.multipart_params), function(value, name) {
multipartBlob += dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf;
multipartBlob += unescape(encodeURIComponent(value)) + crlf;
});
mimeType = plupload.mimeTypes[file.name.replace(/^.+\.([^.]+)/, '$1').toLowerCase()] || 'application/octet-stream';
// Build RFC2388 blob
multipartBlob += dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + up.settings.file_data_name + '"; filename="' + unescape(encodeURIComponent(file.name)) + '"' + crlf +
'Content-Type: ' + mimeType + crlf + crlf +
bin + crlf +
dashdash + boundary + dashdash + crlf;
multipartDeltaSize = multipartBlob.length - bin.length;
bin = multipartBlob;
if (xhr.sendAsBinary) { // Gecko
xhr.sendAsBinary(bin);
} else if (features.canSendBinary) { // WebKit with typed arrays support
var ui8a = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) {
ui8a[i] = (bin.charCodeAt(i) & 0xff);
}
xhr.send(ui8a.buffer);
}
return; // will return from here only if shouldn't send binary
}
}
// if no multipart, or last resort, send as binary stream
url = plupload.buildUrl(up.settings.url, plupload.extend(args, up.settings.multipart_params));
xhr.open("post", url, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream'); // Binary stream header
// Set custom headers
plupload.each(up.settings.headers, function(value, name) {
xhr.setRequestHeader(name, value);
});
xhr.send(bin);
} // prepareAndSend
// File upload finished
if (file.status == plupload.DONE || file.status == plupload.FAILED || up.state == plupload.STOPPED) {
return;
}
// Standard arguments
args = {name : file.target_name || file.name};
// Only add chunking args if needed
if (settings.chunk_size && file.size > settings.chunk_size && (features.chunks || typeof(blob) == 'string')) { // blob will be of type string if it was loaded in memory
chunkSize = settings.chunk_size;
chunks = Math.ceil(file.size / chunkSize);
curChunkSize = Math.min(chunkSize, file.size - (chunk * chunkSize));
// Blob is string so we need to fake chunking, this is not
// ideal since the whole file is loaded into memory
if (typeof(blob) == 'string') {
chunkBlob = blob.substring(chunk * chunkSize, chunk * chunkSize + curChunkSize);
} else {
// Slice the chunk
chunkBlob = w3cBlobSlice(blob, chunk * chunkSize, chunk * chunkSize + curChunkSize);
}
// Setup query string arguments
args.chunk = chunk;
args.chunks = chunks;
} else {
curChunkSize = file.size;
chunkBlob = blob;
}
// workaround Gecko 2,5,6 FormData+Blob bug: https://bugzilla.mozilla.org/show_bug.cgi?id=649150
if (up.settings.multipart && features.multipart && typeof(chunkBlob) !== 'string' && fr && features.cantSendBlobInFormData && features.chunks && up.settings.chunk_size) { // Gecko 2,5,6
fr.onload = function() {
prepareAndSend(fr.result);
}
fr.readAsBinaryString(chunkBlob);
} else {
prepareAndSend(chunkBlob);
}
}
// Start uploading chunks
uploadNextChunk();
}
nativeFile = html5files[file.id];
// Resize image if it's a supported format and resize is enabled
if (features.jpgresize && up.settings.resize && /\.(png|jpg|jpeg)$/i.test(file.name)) {
scaleImage.call(up, file, up.settings.resize, /\.png$/i.test(file.name) ? 'image/png' : 'image/jpeg', function(res) {
// If it was scaled send the scaled image if it failed then
// send the raw image and let the server do the scaling
if (res.success) {
file.size = res.data.length;
sendBinaryBlob(res.data);
} else {
sendBinaryBlob(nativeFile);
}
});
// if there's no way to slice file without preloading it in memory, preload it
} else if (!features.chunks && features.jpgresize) {
readFileAsBinary(nativeFile, sendBinaryBlob);
} else {
sendBinaryBlob(nativeFile);
}
});
uploader.bind('Destroy', function(up) {
var name, element, container = document.body,
elements = {
inputContainer: up.id + '_html5_container',
inputFile: up.id + '_html5',
browseButton: up.settings.browse_button,
dropElm: up.settings.drop_element
};
// Unbind event handlers
for (name in elements) {
element = document.getElementById(elements[name]);
if (element) {
plupload.removeAllEvents(element, up.id);
}
}
plupload.removeAllEvents(document.body, up.id);
if (up.settings.container) {
container = document.getElementById(up.settings.container);
}
// Remove mark-up
container.removeChild(document.getElementById(elements.inputContainer));
});
callback({success : true});
}
});
function BinaryReader() {
var II = false, bin;
// Private functions
function read(idx, size) {
var mv = II ? 0 : -8 * (size - 1), sum = 0, i;
for (i = 0; i < size; i++) {
sum |= (bin.charCodeAt(idx + i) << Math.abs(mv + i*8));
}
return sum;
}
function putstr(segment, idx, length) {
var length = arguments.length === 3 ? length : bin.length - idx - 1;
bin = bin.substr(0, idx) + segment + bin.substr(length + idx);
}
function write(idx, num, size) {
var str = '', mv = II ? 0 : -8 * (size - 1), i;
for (i = 0; i < size; i++) {
str += String.fromCharCode((num >> Math.abs(mv + i*8)) & 255);
}
putstr(str, idx, size);
}
// Public functions
return {
II: function(order) {
if (order === undef) {
return II;
} else {
II = order;
}
},
init: function(binData) {
II = false;
bin = binData;
},
SEGMENT: function(idx, length, segment) {
switch (arguments.length) {
case 1:
return bin.substr(idx, bin.length - idx - 1);
case 2:
return bin.substr(idx, length);
case 3:
putstr(segment, idx, length);
break;
default: return bin;
}
},
BYTE: function(idx) {
return read(idx, 1);
},
SHORT: function(idx) {
return read(idx, 2);
},
LONG: function(idx, num) {
if (num === undef) {
return read(idx, 4);
} else {
write(idx, num, 4);
}
},
SLONG: function(idx) { // 2's complement notation
var num = read(idx, 4);
return (num > 2147483647 ? num - 4294967296 : num);
},
STRING: function(idx, size) {
var str = '';
for (size += idx; idx < size; idx++) {
str += String.fromCharCode(read(idx, 1));
}
return str;
}
};
}
function JPEG_Headers(data) {
var markers = {
0xFFE1: {
app: 'EXIF',
name: 'APP1',
signature: "Exif\0"
},
0xFFE2: {
app: 'ICC',
name: 'APP2',
signature: "ICC_PROFILE\0"
},
0xFFED: {
app: 'IPTC',
name: 'APP13',
signature: "Photoshop 3.0\0"
}
},
headers = [], read, idx, marker = undef, length = 0, limit;
read = new BinaryReader();
read.init(data);
// Check if data is jpeg
if (read.SHORT(0) !== 0xFFD8) {
return;
}
idx = 2;
limit = Math.min(1048576, data.length);
while (idx <= limit) {
marker = read.SHORT(idx);
// omit RST (restart) markers
if (marker >= 0xFFD0 && marker <= 0xFFD7) {
idx += 2;
continue;
}
// no headers allowed after SOS marker
if (marker === 0xFFDA || marker === 0xFFD9) {
break;
}
length = read.SHORT(idx + 2) + 2;
if (markers[marker] &&
read.STRING(idx + 4, markers[marker].signature.length) === markers[marker].signature) {
headers.push({
hex: marker,
app: markers[marker].app.toUpperCase(),
name: markers[marker].name.toUpperCase(),
start: idx,
length: length,
segment: read.SEGMENT(idx, length)
});
}
idx += length;
}
read.init(null); // free memory
return {
headers: headers,
restore: function(data) {
read.init(data);
// Check if data is jpeg
var jpegHeaders = new JPEG_Headers(data);
if (!jpegHeaders['headers']) {
return false;
}
// Delete any existing headers that need to be replaced
for (var i = jpegHeaders['headers'].length; i > 0; i--) {
var hdr = jpegHeaders['headers'][i - 1];
read.SEGMENT(hdr.start, hdr.length, '')
}
jpegHeaders.purge();
idx = read.SHORT(2) == 0xFFE0 ? 4 + read.SHORT(4) : 2;
for (var i = 0, max = headers.length; i < max; i++) {
read.SEGMENT(idx, 0, headers[i].segment);
idx += headers[i].length;
}
return read.SEGMENT();
},
get: function(app) {
var array = [];
for (var i = 0, max = headers.length; i < max; i++) {
if (headers[i].app === app.toUpperCase()) {
array.push(headers[i].segment);
}
}
return array;
},
set: function(app, segment) {
var array = [];
if (typeof(segment) === 'string') {
array.push(segment);
} else {
array = segment;