/
dropzone.js
2311 lines (2041 loc) · 65.6 KB
/
dropzone.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
import Emitter from "./emitter.js";
import defaultOptions from "./options.js";
export default class Dropzone extends Emitter {
static initClass() {
// Exposing the emitter class, mainly for tests
this.prototype.Emitter = Emitter;
/*
This is a list of all available events you can register on a dropzone object.
You can register an event handler like this:
dropzone.on("dragEnter", function() { });
*/
this.prototype.events = [
"drop",
"dragstart",
"dragend",
"dragenter",
"dragover",
"dragleave",
"addedfile",
"addedfiles",
"removedfile",
"thumbnail",
"error",
"errormultiple",
"processing",
"processingmultiple",
"uploadprogress",
"totaluploadprogress",
"sending",
"sendingmultiple",
"success",
"successmultiple",
"canceled",
"canceledmultiple",
"complete",
"completemultiple",
"reset",
"maxfilesexceeded",
"maxfilesreached",
"queuecomplete",
];
this.prototype._thumbnailQueue = [];
this.prototype._processingThumbnail = false;
}
// global utility
static extend(target, ...objects) {
for (let object of objects) {
for (let key in object) {
let val = object[key];
target[key] = val;
}
}
return target;
}
constructor(el, options) {
super();
let fallback, left;
this.element = el;
// For backwards compatibility since the version was in the prototype previously
this.version = Dropzone.version;
this.clickableElements = [];
this.listeners = [];
this.files = []; // All files
if (typeof this.element === "string") {
this.element = document.querySelector(this.element);
}
// Not checking if instance of HTMLElement or Element since IE9 is extremely weird.
if (!this.element || this.element.nodeType == null) {
throw new Error("Invalid dropzone element.");
}
if (this.element.dropzone) {
throw new Error("Dropzone already attached.");
}
// Now add this dropzone to the instances.
Dropzone.instances.push(this);
// Put the dropzone inside the element itself.
this.element.dropzone = this;
let elementOptions =
(left = Dropzone.optionsForElement(this.element)) != null ? left : {};
this.options = Dropzone.extend(
{},
defaultOptions,
elementOptions,
options != null ? options : {}
);
this.options.previewTemplate = this.options.previewTemplate.replace(
/\n*/g,
""
);
// If the browser failed, just call the fallback and leave
if (this.options.forceFallback || !Dropzone.isBrowserSupported()) {
return this.options.fallback.call(this);
}
// @options.url = @element.getAttribute "action" unless @options.url?
if (this.options.url == null) {
this.options.url = this.element.getAttribute("action");
}
if (!this.options.url) {
throw new Error("No URL provided.");
}
if (this.options.acceptedFiles && this.options.acceptedMimeTypes) {
throw new Error(
"You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."
);
}
if (this.options.uploadMultiple && this.options.chunking) {
throw new Error("You cannot set both: uploadMultiple and chunking.");
}
// Backwards compatibility
if (this.options.acceptedMimeTypes) {
this.options.acceptedFiles = this.options.acceptedMimeTypes;
delete this.options.acceptedMimeTypes;
}
// Backwards compatibility
if (this.options.renameFilename != null) {
this.options.renameFile = (file) =>
this.options.renameFilename.call(this, file.name, file);
}
if (typeof this.options.method === "string") {
this.options.method = this.options.method.toUpperCase();
}
if ((fallback = this.getExistingFallback()) && fallback.parentNode) {
// Remove the fallback
fallback.parentNode.removeChild(fallback);
}
// Display previews in the previewsContainer element or the Dropzone element unless explicitly set to false
if (this.options.previewsContainer !== false) {
if (this.options.previewsContainer) {
this.previewsContainer = Dropzone.getElement(
this.options.previewsContainer,
"previewsContainer"
);
} else {
this.previewsContainer = this.element;
}
}
if (this.options.clickable) {
if (this.options.clickable === true) {
this.clickableElements = [this.element];
} else {
this.clickableElements = Dropzone.getElements(
this.options.clickable,
"clickable"
);
}
}
this.init();
}
// Returns all files that have been accepted
getAcceptedFiles() {
return this.files.filter((file) => file.accepted).map((file) => file);
}
// Returns all files that have been rejected
// Not sure when that's going to be useful, but added for completeness.
getRejectedFiles() {
return this.files.filter((file) => !file.accepted).map((file) => file);
}
getFilesWithStatus(status) {
return this.files
.filter((file) => file.status === status)
.map((file) => file);
}
// Returns all files that are in the queue
getQueuedFiles() {
return this.getFilesWithStatus(Dropzone.QUEUED);
}
getUploadingFiles() {
return this.getFilesWithStatus(Dropzone.UPLOADING);
}
getAddedFiles() {
return this.getFilesWithStatus(Dropzone.ADDED);
}
// Files that are either queued or uploading
getActiveFiles() {
return this.files
.filter(
(file) =>
file.status === Dropzone.UPLOADING || file.status === Dropzone.QUEUED
)
.map((file) => file);
}
// The function that gets called when Dropzone is initialized. You
// can (and should) setup event listeners inside this function.
init() {
// In case it isn't set already
if (this.element.tagName === "form") {
this.element.setAttribute("enctype", "multipart/form-data");
}
if (
this.element.classList.contains("dropzone") &&
!this.element.querySelector(".dz-message")
) {
this.element.appendChild(
Dropzone.createElement(
`<div class="dz-default dz-message"><button class="dz-button" type="button">${this.options.dictDefaultMessage}</button></div>`
)
);
}
if (this.clickableElements.length) {
let setupHiddenFileInput = () => {
if (this.hiddenFileInput) {
this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput);
}
this.hiddenFileInput = document.createElement("input");
this.hiddenFileInput.setAttribute("type", "file");
if (this.options.maxFiles === null || this.options.maxFiles > 1) {
this.hiddenFileInput.setAttribute("multiple", "multiple");
}
this.hiddenFileInput.className = "dz-hidden-input";
if (this.options.acceptedFiles !== null) {
this.hiddenFileInput.setAttribute(
"accept",
this.options.acceptedFiles
);
}
if (this.options.capture !== null) {
this.hiddenFileInput.setAttribute("capture", this.options.capture);
}
// Making sure that no one can "tab" into this field.
this.hiddenFileInput.setAttribute("tabindex", "-1");
// Not setting `display="none"` because some browsers don't accept clicks
// on elements that aren't displayed.
this.hiddenFileInput.style.visibility = "hidden";
this.hiddenFileInput.style.position = "absolute";
this.hiddenFileInput.style.top = "0";
this.hiddenFileInput.style.left = "0";
this.hiddenFileInput.style.height = "0";
this.hiddenFileInput.style.width = "0";
Dropzone.getElement(
this.options.hiddenInputContainer,
"hiddenInputContainer"
).appendChild(this.hiddenFileInput);
this.hiddenFileInput.addEventListener("change", () => {
let { files } = this.hiddenFileInput;
if (files.length) {
for (let file of files) {
this.addFile(file);
}
}
this.emit("addedfiles", files);
setupHiddenFileInput();
});
};
setupHiddenFileInput();
}
this.URL = window.URL !== null ? window.URL : window.webkitURL;
// Setup all event listeners on the Dropzone object itself.
// They're not in @setupEventListeners() because they shouldn't be removed
// again when the dropzone gets disabled.
for (let eventName of this.events) {
this.on(eventName, this.options[eventName]);
}
this.on("uploadprogress", () => this.updateTotalUploadProgress());
this.on("removedfile", () => this.updateTotalUploadProgress());
this.on("canceled", (file) => this.emit("complete", file));
// Emit a `queuecomplete` event if all files finished uploading.
this.on("complete", (file) => {
if (
this.getAddedFiles().length === 0 &&
this.getUploadingFiles().length === 0 &&
this.getQueuedFiles().length === 0
) {
// This needs to be deferred so that `queuecomplete` really triggers after `complete`
return setTimeout(() => this.emit("queuecomplete"), 0);
}
});
const containsFiles = function (e) {
if (e.dataTransfer.types) {
// Because e.dataTransfer.types is an Object in
// IE, we need to iterate like this instead of
// using e.dataTransfer.types.some()
for (var i = 0; i < e.dataTransfer.types.length; i++) {
if (e.dataTransfer.types[i] === "Files") return true;
}
}
return false;
};
let noPropagation = function (e) {
// If there are no files, we don't want to stop
// propagation so we don't interfere with other
// drag and drop behaviour.
if (!containsFiles(e)) return;
e.stopPropagation();
if (e.preventDefault) {
return e.preventDefault();
} else {
return (e.returnValue = false);
}
};
// Create the listeners
this.listeners = [
{
element: this.element,
events: {
dragstart: (e) => {
return this.emit("dragstart", e);
},
dragenter: (e) => {
noPropagation(e);
return this.emit("dragenter", e);
},
dragover: (e) => {
// Makes it possible to drag files from chrome's download bar
// http://stackoverflow.com/questions/19526430/drag-and-drop-file-uploads-from-chrome-downloads-bar
// Try is required to prevent bug in Internet Explorer 11 (SCRIPT65535 exception)
let efct;
try {
efct = e.dataTransfer.effectAllowed;
} catch (error) {}
e.dataTransfer.dropEffect =
"move" === efct || "linkMove" === efct ? "move" : "copy";
noPropagation(e);
return this.emit("dragover", e);
},
dragleave: (e) => {
return this.emit("dragleave", e);
},
drop: (e) => {
noPropagation(e);
return this.drop(e);
},
dragend: (e) => {
return this.emit("dragend", e);
},
},
// This is disabled right now, because the browsers don't implement it properly.
// "paste": (e) =>
// noPropagation e
// @paste e
},
];
this.clickableElements.forEach((clickableElement) => {
return this.listeners.push({
element: clickableElement,
events: {
click: (evt) => {
// Only the actual dropzone or the message element should trigger file selection
if (
clickableElement !== this.element ||
evt.target === this.element ||
Dropzone.elementInside(
evt.target,
this.element.querySelector(".dz-message")
)
) {
this.hiddenFileInput.click(); // Forward the click
}
return true;
},
},
});
});
this.enable();
return this.options.init.call(this);
}
// Not fully tested yet
destroy() {
this.disable();
this.removeAllFiles(true);
if (
this.hiddenFileInput != null ? this.hiddenFileInput.parentNode : undefined
) {
this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput);
this.hiddenFileInput = null;
}
delete this.element.dropzone;
return Dropzone.instances.splice(Dropzone.instances.indexOf(this), 1);
}
updateTotalUploadProgress() {
let totalUploadProgress;
let totalBytesSent = 0;
let totalBytes = 0;
let activeFiles = this.getActiveFiles();
if (activeFiles.length) {
for (let file of this.getActiveFiles()) {
totalBytesSent += file.upload.bytesSent;
totalBytes += file.upload.total;
}
totalUploadProgress = (100 * totalBytesSent) / totalBytes;
} else {
totalUploadProgress = 100;
}
return this.emit(
"totaluploadprogress",
totalUploadProgress,
totalBytes,
totalBytesSent
);
}
// @options.paramName can be a function taking one parameter rather than a string.
// A parameter name for a file is obtained simply by calling this with an index number.
_getParamName(n) {
if (typeof this.options.paramName === "function") {
return this.options.paramName(n);
} else {
return `${this.options.paramName}${
this.options.uploadMultiple ? `[${n}]` : ""
}`;
}
}
// If @options.renameFile is a function,
// the function will be used to rename the file.name before appending it to the formData
_renameFile(file) {
if (typeof this.options.renameFile !== "function") {
return file.name;
}
return this.options.renameFile(file);
}
// Returns a form that can be used as fallback if the browser does not support DragnDrop
//
// If the dropzone is already a form, only the input field and button are returned. Otherwise a complete form element is provided.
// This code has to pass in IE7 :(
getFallbackForm() {
let existingFallback, form;
if ((existingFallback = this.getExistingFallback())) {
return existingFallback;
}
let fieldsString = '<div class="dz-fallback">';
if (this.options.dictFallbackText) {
fieldsString += `<p>${this.options.dictFallbackText}</p>`;
}
fieldsString += `<input type="file" name="${this._getParamName(0)}" ${
this.options.uploadMultiple ? 'multiple="multiple"' : undefined
} /><input type="submit" value="Upload!"></div>`;
let fields = Dropzone.createElement(fieldsString);
if (this.element.tagName !== "FORM") {
form = Dropzone.createElement(
`<form action="${this.options.url}" enctype="multipart/form-data" method="${this.options.method}"></form>`
);
form.appendChild(fields);
} else {
// Make sure that the enctype and method attributes are set properly
this.element.setAttribute("enctype", "multipart/form-data");
this.element.setAttribute("method", this.options.method);
}
return form != null ? form : fields;
}
// Returns the fallback elements if they exist already
//
// This code has to pass in IE7 :(
getExistingFallback() {
let getFallback = function (elements) {
for (let el of elements) {
if (/(^| )fallback($| )/.test(el.className)) {
return el;
}
}
};
for (let tagName of ["div", "form"]) {
var fallback;
if (
(fallback = getFallback(this.element.getElementsByTagName(tagName)))
) {
return fallback;
}
}
}
// Activates all listeners stored in @listeners
setupEventListeners() {
return this.listeners.map((elementListeners) =>
(() => {
let result = [];
for (let event in elementListeners.events) {
let listener = elementListeners.events[event];
result.push(
elementListeners.element.addEventListener(event, listener, false)
);
}
return result;
})()
);
}
// Deactivates all listeners stored in @listeners
removeEventListeners() {
return this.listeners.map((elementListeners) =>
(() => {
let result = [];
for (let event in elementListeners.events) {
let listener = elementListeners.events[event];
result.push(
elementListeners.element.removeEventListener(event, listener, false)
);
}
return result;
})()
);
}
// Removes all event listeners and cancels all files in the queue or being processed.
disable() {
this.clickableElements.forEach((element) =>
element.classList.remove("dz-clickable")
);
this.removeEventListeners();
this.disabled = true;
return this.files.map((file) => this.cancelUpload(file));
}
enable() {
delete this.disabled;
this.clickableElements.forEach((element) =>
element.classList.add("dz-clickable")
);
return this.setupEventListeners();
}
// Returns a nicely formatted filesize
filesize(size) {
let selectedSize = 0;
let selectedUnit = "b";
if (size > 0) {
let units = ["tb", "gb", "mb", "kb", "b"];
for (let i = 0; i < units.length; i++) {
let unit = units[i];
let cutoff = Math.pow(this.options.filesizeBase, 4 - i) / 10;
if (size >= cutoff) {
selectedSize = size / Math.pow(this.options.filesizeBase, 4 - i);
selectedUnit = unit;
break;
}
}
selectedSize = Math.round(10 * selectedSize) / 10; // Cutting of digits
}
return `<strong>${selectedSize}</strong> ${this.options.dictFileSizeUnits[selectedUnit]}`;
}
// Adds or removes the `dz-max-files-reached` class from the form.
_updateMaxFilesReachedClass() {
if (
this.options.maxFiles != null &&
this.getAcceptedFiles().length >= this.options.maxFiles
) {
if (this.getAcceptedFiles().length === this.options.maxFiles) {
this.emit("maxfilesreached", this.files);
}
return this.element.classList.add("dz-max-files-reached");
} else {
return this.element.classList.remove("dz-max-files-reached");
}
}
drop(e) {
if (!e.dataTransfer) {
return;
}
this.emit("drop", e);
// Convert the FileList to an Array
// This is necessary for IE11
let files = [];
for (let i = 0; i < e.dataTransfer.files.length; i++) {
files[i] = e.dataTransfer.files[i];
}
// Even if it's a folder, files.length will contain the folders.
if (files.length) {
let { items } = e.dataTransfer;
if (items && items.length && items[0].webkitGetAsEntry != null) {
// The browser supports dropping of folders, so handle items instead of files
this._addFilesFromItems(items);
} else {
this.handleFiles(files);
}
}
this.emit("addedfiles", files);
}
paste(e) {
if (
__guard__(e != null ? e.clipboardData : undefined, (x) => x.items) == null
) {
return;
}
this.emit("paste", e);
let { items } = e.clipboardData;
if (items.length) {
return this._addFilesFromItems(items);
}
}
handleFiles(files) {
for (let file of files) {
this.addFile(file);
}
}
// When a folder is dropped (or files are pasted), items must be handled
// instead of files.
_addFilesFromItems(items) {
return (() => {
let result = [];
for (let item of items) {
var entry;
if (
item.webkitGetAsEntry != null &&
(entry = item.webkitGetAsEntry())
) {
if (entry.isFile) {
result.push(this.addFile(item.getAsFile()));
} else if (entry.isDirectory) {
// Append all files from that directory to files
result.push(this._addFilesFromDirectory(entry, entry.name));
} else {
result.push(undefined);
}
} else if (item.getAsFile != null) {
if (item.kind == null || item.kind === "file") {
result.push(this.addFile(item.getAsFile()));
} else {
result.push(undefined);
}
} else {
result.push(undefined);
}
}
return result;
})();
}
// Goes through the directory, and adds each file it finds recursively
_addFilesFromDirectory(directory, path) {
let dirReader = directory.createReader();
let errorHandler = (error) =>
__guardMethod__(console, "log", (o) => o.log(error));
var readEntries = () => {
return dirReader.readEntries((entries) => {
if (entries.length > 0) {
for (let entry of entries) {
if (entry.isFile) {
entry.file((file) => {
if (
this.options.ignoreHiddenFiles &&
file.name.substring(0, 1) === "."
) {
return;
}
file.fullPath = `${path}/${file.name}`;
return this.addFile(file);
});
} else if (entry.isDirectory) {
this._addFilesFromDirectory(entry, `${path}/${entry.name}`);
}
}
// Recursively call readEntries() again, since browser only handle
// the first 100 entries.
// See: https://developer.mozilla.org/en-US/docs/Web/API/DirectoryReader#readEntries
readEntries();
}
return null;
}, errorHandler);
};
return readEntries();
}
// If `done()` is called without argument the file is accepted
// If you call it with an error message, the file is rejected
// (This allows for asynchronous validation)
//
// This function checks the filesize, and if the file.type passes the
// `acceptedFiles` check.
accept(file, done) {
if (
this.options.maxFilesize &&
file.size > this.options.maxFilesize * 1024 * 1024
) {
done(
this.options.dictFileTooBig
.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100)
.replace("{{maxFilesize}}", this.options.maxFilesize)
);
} else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) {
done(this.options.dictInvalidFileType);
} else if (
this.options.maxFiles != null &&
this.getAcceptedFiles().length >= this.options.maxFiles
) {
done(
this.options.dictMaxFilesExceeded.replace(
"{{maxFiles}}",
this.options.maxFiles
)
);
this.emit("maxfilesexceeded", file);
} else {
this.options.accept.call(this, file, done);
}
}
addFile(file) {
file.upload = {
uuid: Dropzone.uuidv4(),
progress: 0,
// Setting the total upload size to file.size for the beginning
// It's actual different than the size to be transmitted.
total: file.size,
bytesSent: 0,
filename: this._renameFile(file),
// Not setting chunking information here, because the acutal data — and
// thus the chunks — might change if `options.transformFile` is set
// and does something to the data.
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
this.accept(file, (error) => {
if (error) {
file.accepted = false;
this._errorProcessing([file], error); // Will set the file.status
} else {
file.accepted = true;
if (this.options.autoQueue) {
this.enqueueFile(file);
} // Will set .accepted = true
}
this._updateMaxFilesReachedClass();
});
}
// Wrapper for enqueueFile
enqueueFiles(files) {
for (let file of files) {
this.enqueueFile(file);
}
return null;
}
enqueueFile(file) {
if (file.status === Dropzone.ADDED && file.accepted === true) {
file.status = Dropzone.QUEUED;
if (this.options.autoProcessQueue) {
return setTimeout(() => this.processQueue(), 0); // Deferring the call
}
} else {
throw new Error(
"This file can't be queued because it has already been processed or was rejected."
);
}
}
_enqueueThumbnail(file) {
if (
this.options.createImageThumbnails &&
file.type.match(/image.*/) &&
file.size <= this.options.maxThumbnailFilesize * 1024 * 1024
) {
this._thumbnailQueue.push(file);
return setTimeout(() => this._processThumbnailQueue(), 0); // Deferring the call
}
}
_processThumbnailQueue() {
if (this._processingThumbnail || this._thumbnailQueue.length === 0) {
return;
}
this._processingThumbnail = true;
let file = this._thumbnailQueue.shift();
return this.createThumbnail(
file,
this.options.thumbnailWidth,
this.options.thumbnailHeight,
this.options.thumbnailMethod,
true,
(dataUrl) => {
this.emit("thumbnail", file, dataUrl);
this._processingThumbnail = false;
return this._processThumbnailQueue();
}
);
}
// Can be called by the user to remove a file
removeFile(file) {
if (file.status === Dropzone.UPLOADING) {
this.cancelUpload(file);
}
this.files = without(this.files, file);
this.emit("removedfile", file);
if (this.files.length === 0) {
return this.emit("reset");
}
}
// Removes all files that aren't currently processed from the list
removeAllFiles(cancelIfNecessary) {
// Create a copy of files since removeFile() changes the @files array.
if (cancelIfNecessary == null) {
cancelIfNecessary = false;
}
for (let file of this.files.slice()) {
if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) {
this.removeFile(file);
}
}
return null;
}
// Resizes an image before it gets sent to the server. This function is the default behavior of
// `options.transformFile` if `resizeWidth` or `resizeHeight` are set. The callback is invoked with
// the resized blob.
resizeImage(file, width, height, resizeMethod, callback) {
return this.createThumbnail(
file,
width,
height,
resizeMethod,
true,
(dataUrl, canvas) => {
if (canvas == null) {
// The image has not been resized
return callback(file);
} else {
let { resizeMimeType } = this.options;
if (resizeMimeType == null) {
resizeMimeType = file.type;
}
let resizedDataURL = canvas.toDataURL(
resizeMimeType,
this.options.resizeQuality
);
if (
resizeMimeType === "image/jpeg" ||
resizeMimeType === "image/jpg"
) {
// Now add the original EXIF information
resizedDataURL = ExifRestore.restore(file.dataURL, resizedDataURL);
}
return callback(Dropzone.dataURItoBlob(resizedDataURL));
}
}
);
}
createThumbnail(file, width, height, resizeMethod, fixOrientation, callback) {
let fileReader = new FileReader();
fileReader.onload = () => {
file.dataURL = fileReader.result;
// Don't bother creating a thumbnail for SVG images since they're vector
if (file.type === "image/svg+xml") {
if (callback != null) {
callback(fileReader.result);
}
return;
}
this.createThumbnailFromUrl(
file,
width,
height,
resizeMethod,
fixOrientation,
callback
);
};
fileReader.readAsDataURL(file);
}
// `mockFile` needs to have these attributes:
//
// { name: 'name', size: 12345, imageUrl: '' }
//
// `callback` will be invoked when the image has been downloaded and displayed.
// `crossOrigin` will be added to the `img` tag when accessing the file.
displayExistingFile(
mockFile,
imageUrl,
callback,
crossOrigin,
resizeThumbnail = true
) {
this.emit("addedfile", mockFile);
this.emit("complete", mockFile);
if (!resizeThumbnail) {
this.emit("thumbnail", mockFile, imageUrl);
if (callback) callback();
} else {
let onDone = (thumbnail) => {
this.emit("thumbnail", mockFile, thumbnail);
if (callback) callback();
};
mockFile.dataURL = imageUrl;
this.createThumbnailFromUrl(
mockFile,
this.options.thumbnailWidth,
this.options.thumbnailHeight,
this.options.resizeMethod,
this.options.fixOrientation,
onDone,
crossOrigin
);
}
}
createThumbnailFromUrl(
file,
width,
height,
resizeMethod,
fixOrientation,
callback,
crossOrigin
) {
// Not using `new Image` here because of a bug in latest Chrome versions.
// See https://github.com/enyo/dropzone/pull/226
let img = document.createElement("img");