-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
fileupload.ts
executable file
·911 lines (802 loc) · 33 KB
/
fileupload.ts
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
import { CommonModule, DOCUMENT, isPlatformBrowser } from '@angular/common';
import { HttpClient, HttpClientModule, HttpEvent, HttpEventType, HttpHeaders } from '@angular/common/http';
import {
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Inject,
Input,
NgModule,
NgZone,
OnDestroy,
OnInit,
Output,
PLATFORM_ID,
QueryList,
Renderer2,
TemplateRef,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { BlockableUI, Message, PrimeNGConfig, PrimeTemplate, SharedModule, TranslationKeys } from 'primeng/api';
import { ButtonModule } from 'primeng/button';
import { DomHandler } from 'primeng/dom';
import { PlusIcon } from 'primeng/icons/plus';
import { TimesIcon } from 'primeng/icons/times';
import { UploadIcon } from 'primeng/icons/upload';
import { MessagesModule } from 'primeng/messages';
import { ProgressBarModule } from 'primeng/progressbar';
import { RippleModule } from 'primeng/ripple';
import { VoidListener } from 'primeng/ts-helpers';
import { Subscription } from 'rxjs';
import { FileBeforeUploadEvent, FileProgressEvent, FileRemoveEvent, FileSelectEvent, FileSendEvent, FileUploadErrorEvent, FileUploadEvent, FileUploadHandlerEvent } from './fileupload.interface';
/**
* FileUpload is an advanced uploader with dragdrop support, multi file uploads, auto uploading, progress tracking and validations.
* @group Components
*/
@Component({
selector: 'p-fileUpload',
template: `
<div [ngClass]="'p-fileupload p-fileupload-advanced p-component'" [ngStyle]="style" [class]="styleClass" *ngIf="mode === 'advanced'" [attr.data-pc-name]="'fileupload'" [attr.data-pc-section]="'root'">
<div class="p-fileupload-buttonbar" [attr.data-pc-section]="'buttonbar'">
<span
class="p-button p-component p-fileupload-choose"
[ngClass]="{ 'p-focus': focus, 'p-disabled': disabled || isChooseDisabled() }"
(focus)="onFocus()"
(blur)="onBlur()"
pRipple
(click)="choose()"
(keydown.enter)="choose()"
tabindex="0"
[class]="chooseStyleClass"
[attr.data-pc-section]="'choosebutton'"
>
<input #advancedfileinput type="file" (change)="onFileSelect($event)" [multiple]="multiple" [accept]="accept" [disabled]="disabled || isChooseDisabled()" [attr.title]="''" [attr.data-pc-section]="'input'" />
<span *ngIf="chooseIcon" [ngClass]="'p-button-icon p-button-icon-left'" [class]="chooseIcon" [attr.aria-label]="true" [attr.data-pc-section]="'chooseicon'"></span>
<ng-container *ngIf="!chooseIcon">
<PlusIcon *ngIf="!chooseIconTemplate" [styleClass]="'p-button-icon p-button-icon-left'" [attr.aria-label]="true" [attr.data-pc-section]="'chooseicon'" />
<span *ngIf="chooseIconTemplate" class="p-button-icon p-button-icon-left" [attr.aria-label]="true" [attr.data-pc-section]="'chooseicon'">
<ng-template *ngTemplateOutlet="chooseIconTemplate"></ng-template>
</span>
</ng-container>
<span class="p-button-label" [attr.data-pc-section]="'choosebuttonlabel'">{{ chooseButtonLabel }}</span>
</span>
<p-button *ngIf="!auto && showUploadButton" type="button" [label]="uploadButtonLabel" (onClick)="upload()" [disabled]="!hasFiles() || isFileLimitExceeded()" [styleClass]="uploadStyleClass">
<span *ngIf="uploadIcon" [ngClass]="uploadIcon" [attr.aria-hidden]="true" class="p-button-icon p-button-icon-left"></span>
<ng-container *ngIf="!uploadIcon">
<UploadIcon *ngIf="!uploadIconTemplate" [styleClass]="'p-button-icon p-button-icon-left'" />
<span *ngIf="uploadIconTemplate" class="p-button-icon p-button-icon-left" [attr.aria-hidden]="true">
<ng-template *ngTemplateOutlet="uploadIconTemplate"></ng-template>
</span>
</ng-container>
</p-button>
<p-button *ngIf="!auto && showCancelButton" type="button" [label]="cancelButtonLabel" (onClick)="clear()" [disabled]="!hasFiles() || uploading" [styleClass]="cancelStyleClass">
<span *ngIf="cancelIcon" [ngClass]="cancelIcon" class="p-button-icon p-button-icon-left"></span>
<ng-container *ngIf="!cancelIcon">
<TimesIcon *ngIf="!cancelIconTemplate" [styleClass]="'p-button-icon p-button-icon-left'" [attr.aria-hidden]="true" />
<span *ngIf="cancelIconTemplate" class="p-button-icon p-button-icon-left" [attr.aria-hidden]="true">
<ng-template *ngTemplateOutlet="cancelIconTemplate"></ng-template>
</span>
</ng-container>
</p-button>
<ng-container *ngTemplateOutlet="toolbarTemplate"></ng-container>
</div>
<div #content class="p-fileupload-content" (dragenter)="onDragEnter($event)" (dragleave)="onDragLeave($event)" (drop)="onDrop($event)" [attr.data-pc-section]="'content'">
<p-progressBar [value]="progress" [showValue]="false" *ngIf="hasFiles()"></p-progressBar>
<p-messages [value]="msgs" [enableService]="false"></p-messages>
<div class="p-fileupload-files" *ngIf="hasFiles()">
<div *ngIf="!fileTemplate">
<div class="p-fileupload-row" *ngFor="let file of files; let i = index">
<div><img [src]="file.objectURL" *ngIf="isImage(file)" [width]="previewWidth" (error)="imageError($event)" /></div>
<div class="p-fileupload-filename">{{ file.name }}</div>
<div>{{ formatSize(file.size) }}</div>
<div>
<button type="button" pButton (click)="remove($event, i)" [disabled]="uploading" class="p-button-icon-only" [class]="removeStyleClass">
<TimesIcon *ngIf="!cancelIconTemplate" />
<ng-template *ngTemplateOutlet="cancelIconTemplate"></ng-template>
</button>
</div>
</div>
</div>
<div *ngIf="fileTemplate">
<ng-template ngFor [ngForOf]="files" [ngForTemplate]="fileTemplate"></ng-template>
</div>
</div>
<ng-container *ngTemplateOutlet="contentTemplate; context: { $implicit: files }"></ng-container>
</div>
</div>
<div class="p-fileupload p-fileupload-basic p-component" *ngIf="mode === 'basic'" [attr.data-pc-name]="'fileupload'">
<p-messages [value]="msgs" [enableService]="false"></p-messages>
<span
[ngClass]="{ 'p-button p-component p-fileupload-choose': true, 'p-button-icon-only': !basicButtonLabel, 'p-fileupload-choose-selected': hasFiles(), 'p-focus': focus, 'p-disabled': disabled }"
[ngStyle]="style"
[class]="styleClass"
(click)="onBasicUploaderClick()"
(keydown)="onBasicKeydown($event)"
tabindex="0"
pRipple
[attr.data-pc-section]="'choosebutton'"
>
<ng-container *ngIf="hasFiles() && !auto; else chooseSection">
<span *ngIf="uploadIcon" class="p-button-icon p-button-icon-left" [ngClass]="uploadIcon"></span>
<ng-container *ngIf="!uploadIcon">
<UploadIcon *ngIf="!uploadIconTemplate" [styleClass]="'p-button-icon p-button-icon-left'" />
<span *ngIf="uploadIconTemplate" class="p-button-icon p-button-icon-left">
<ng-template *ngTemplateOutlet="uploadIconTemplate"></ng-template>
</span>
</ng-container>
</ng-container>
<ng-template #chooseSection>
<span *ngIf="chooseIcon" class="p-button-icon p-button-icon-left pi" [ngClass]="chooseIcon"></span>
<ng-container *ngIf="!chooseIcon">
<PlusIcon [styleClass]="'p-button-icon p-button-icon-left pi'" *ngIf="!chooseIconTemplate" [attr.aria-hidden]="true" [attr.data-pc-section]="'uploadicon'" />
<span *ngIf="chooseIconTemplate" class="p-button-icon p-button-icon-left pi" [attr.aria-hidden]="true" [attr.data-pc-section]="'uploadicon'">
<ng-template *ngTemplateOutlet="chooseIconTemplate"></ng-template>
</span>
</ng-container>
</ng-template>
<span *ngIf="basicButtonLabel" class="p-button-label" [attr.data-pc-section]="'label'">{{ basicButtonLabel }}</span>
<input #basicfileinput type="file" [accept]="accept" [multiple]="multiple" [disabled]="disabled" (change)="onFileSelect($event)" *ngIf="!hasFiles()" (focus)="onFocus()" (blur)="onBlur()" [attr.data-pc-section]="'input'" />
</span>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
styleUrls: ['./fileupload.css'],
host: {
class: 'p-element'
}
})
export class FileUpload implements AfterViewInit, AfterContentInit, OnInit, OnDestroy, BlockableUI {
/**
* Name of the request parameter to identify the files at backend.
* @group Props
*/
@Input() name: string | undefined;
/**
* Remote url to upload the files.
* @group Props
*/
@Input() url: string | undefined;
/**
* HTTP method to send the files to the url such as "post" and "put".
* @group Props
*/
@Input() method: 'post' | 'put' | undefined = 'post';
/**
* Used to select multiple files at once from file dialog.
* @group Props
*/
@Input() multiple: boolean | undefined;
/**
* Comma-separated list of pattern to restrict the allowed file types. Can be any combination of either the MIME types (such as "image/*") or the file extensions (such as ".jpg").
* @group Props
*/
@Input() accept: string | undefined;
/**
* Disables the upload functionality.
* @group Props
*/
@Input() disabled: boolean | undefined;
/**
* When enabled, upload begins automatically after selection is completed.
* @group Props
*/
@Input() auto: boolean | undefined;
/**
* Cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates.
* @group Props
*/
@Input() withCredentials: boolean | undefined;
/**
* Maximum file size allowed in bytes.
* @group Props
*/
@Input() maxFileSize: number | undefined;
/**
* Summary message of the invalid file size.
* @group Props
*/
@Input() invalidFileSizeMessageSummary: string = '{0}: Invalid file size, ';
/**
* Detail message of the invalid file size.
* @group Props
*/
@Input() invalidFileSizeMessageDetail: string = 'maximum upload size is {0}.';
/**
* Summary message of the invalid file type.
* @group Props
*/
@Input() invalidFileTypeMessageSummary: string = '{0}: Invalid file type, ';
/**
* Detail message of the invalid file type.
* @group Props
*/
@Input() invalidFileTypeMessageDetail: string = 'allowed file types: {0}.';
/**
* Detail message of the invalid file type.
* @group Props
*/
@Input() invalidFileLimitMessageDetail: string = 'limit is {0} at most.';
/**
* Summary message of the invalid file type.
* @group Props
*/
@Input() invalidFileLimitMessageSummary: string = 'Maximum number of files exceeded, ';
/**
* Inline style of the element.
* @group Props
*/
@Input() style: { [klass: string]: any } | null | undefined;
/**
* Class of the element.
* @group Props
*/
@Input() styleClass: string | undefined;
/**
* Width of the image thumbnail in pixels.
* @group Props
*/
@Input() previewWidth: number = 50;
/**
* Label of the choose button. Defaults to PrimeNG Locale configuration.
* @group Props
*/
@Input() chooseLabel: string | undefined;
/**
* Label of the upload button. Defaults to PrimeNG Locale configuration.
* @group Props
*/
@Input() uploadLabel: string | undefined;
/**
* Label of the cancel button. Defaults to PrimeNG Locale configuration.
* @group Props
*/
@Input() cancelLabel: string | undefined;
/**
* Icon of the choose button.
* @group Props
*/
@Input() chooseIcon: string | undefined;
/**
* Icon of the upload button.
* @group Props
*/
@Input() uploadIcon: string | undefined;
/**
* Icon of the cancel button.
* @group Props
*/
@Input() cancelIcon: string | undefined;
/**
* Whether to show the upload button.
* @group Props
*/
@Input() showUploadButton: boolean = true;
/**
* Whether to show the cancel button.
* @group Props
*/
@Input() showCancelButton: boolean = true;
/**
* Defines the UI of the component.
* @group Props
*/
@Input() mode: 'advanced' | 'basic' | undefined = 'advanced';
/**
* HttpHeaders class represents the header configuration options for an HTTP request.
* @group Props
*/
@Input() headers: HttpHeaders | undefined;
/**
* Whether to use the default upload or a manual implementation defined in uploadHandler callback. Defaults to PrimeNG Locale configuration.
* @group Props
*/
@Input() customUpload: boolean | undefined;
/**
* Maximum number of files that can be uploaded.
* @group Props
*/
@Input() fileLimit: number | undefined;
/**
* Style class of the upload button.
* @group Props
*/
@Input() uploadStyleClass: string | undefined;
/**
* Style class of the cancel button.
* @group Props
*/
@Input() cancelStyleClass: string | undefined;
/**
* Style class of the remove button.
* @group Props
*/
@Input() removeStyleClass: string | undefined;
/**
* Style class of the choose button.
* @group Props
*/
@Input() chooseStyleClass: string | undefined;
/**
* Callback to invoke before file upload is initialized.
* @param {FileBeforeUploadEvent} event - Custom upload event.
* @group Emits
*/
@Output() onBeforeUpload: EventEmitter<FileBeforeUploadEvent> = new EventEmitter<FileBeforeUploadEvent>();
/**
* An event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream.
* @param {FileSendEvent} event - Custom send event.
* @group Emits
*/
@Output() onSend: EventEmitter<FileSendEvent> = new EventEmitter<FileSendEvent>();
/**
* Callback to invoke when file upload is complete.
* @param {FileUploadEvent} event - Custom upload event.
* @group Emits
*/
@Output() onUpload: EventEmitter<FileUploadEvent> = new EventEmitter<FileUploadEvent>();
/**
* Callback to invoke if file upload fails.
* @param {FileUploadErrorEvent} event - Custom error event.
* @group Emits
*/
@Output() onError: EventEmitter<FileUploadErrorEvent> = new EventEmitter<FileUploadErrorEvent>();
/**
* Callback to invoke when files in queue are removed without uploading using clear all button.
* @param {Event} event - Browser event.
* @group Emits
*/
@Output() onClear: EventEmitter<Event> = new EventEmitter<Event>();
/**
* Callback to invoke when a file is removed without uploading using clear button of a file.
* @param {FileRemoveEvent} event - Remove event.
* @group Emits
*/
@Output() onRemove: EventEmitter<FileRemoveEvent> = new EventEmitter<FileRemoveEvent>();
/**
* Callback to invoke when files are selected.
* @param {FileSelectEvent} event - Select event.
* @group Emits
*/
@Output() onSelect: EventEmitter<FileSelectEvent> = new EventEmitter<FileSelectEvent>();
/**
* Callback to invoke when files are being uploaded.
* @param {FileProgressEvent} event - Progress event.
* @group Emits
*/
@Output() onProgress: EventEmitter<FileProgressEvent> = new EventEmitter<FileProgressEvent>();
/**
* Callback to invoke in custom upload mode to upload the files manually.
* @param {FileUploadHandlerEvent} event - Upload handler event.
* @group Emits
*/
@Output() uploadHandler: EventEmitter<FileUploadHandlerEvent> = new EventEmitter<FileUploadHandlerEvent>();
/**
* This event is triggered if an error occurs while loading an image file.
* @param {Event} event - Browser event.
* @group Emits
*/
@Output() onImageError: EventEmitter<Event> = new EventEmitter<Event>();
@ContentChildren(PrimeTemplate) templates: QueryList<PrimeTemplate> | undefined;
@ViewChild('advancedfileinput') advancedFileInput: ElementRef | undefined | any;
@ViewChild('basicfileinput') basicFileInput: ElementRef | undefined;
@ViewChild('content') content: ElementRef | undefined;
@Input() set files(files) {
this._files = [];
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (this.validate(file)) {
if (this.isImage(file)) {
(<any>file).objectURL = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(files[i]));
}
this._files.push(files[i]);
}
}
}
get files(): File[] {
return this._files;
}
public get basicButtonLabel(): string {
if (this.auto || !this.hasFiles()) {
return this.chooseLabel as string;
}
return this.uploadLabel ?? this.files[0].name;
}
public _files: File[] = [];
public progress: number = 0;
public dragHighlight: boolean | undefined;
public msgs: Message[] | undefined;
public fileTemplate: TemplateRef<any> | undefined;
public contentTemplate: TemplateRef<any> | undefined;
public toolbarTemplate: TemplateRef<any> | undefined;
chooseIconTemplate: TemplateRef<any> | undefined;
uploadIconTemplate: TemplateRef<any> | undefined;
cancelIconTemplate: TemplateRef<any> | undefined;
public uploadedFileCount: number = 0;
focus: boolean | undefined;
uploading: boolean | undefined;
duplicateIEEvent: boolean | undefined; // flag to recognize duplicate onchange event for file input
translationSubscription: Subscription | undefined;
dragOverListener: VoidListener;
constructor(
@Inject(DOCUMENT) private document: Document,
@Inject(PLATFORM_ID) private platformId: any,
private renderer: Renderer2,
private el: ElementRef,
public sanitizer: DomSanitizer,
public zone: NgZone,
private http: HttpClient,
public cd: ChangeDetectorRef,
public config: PrimeNGConfig
) {}
ngAfterContentInit() {
this.templates?.forEach((item) => {
switch (item.getType()) {
case 'file':
this.fileTemplate = item.template;
break;
case 'content':
this.contentTemplate = item.template;
break;
case 'toolbar':
this.toolbarTemplate = item.template;
break;
case 'chooseicon':
this.chooseIconTemplate = item.template;
break;
case 'uploadicon':
this.uploadIconTemplate = item.template;
break;
case 'cancelicon':
this.cancelIconTemplate = item.template;
break;
default:
this.fileTemplate = item.template;
break;
}
});
}
ngOnInit() {
this.translationSubscription = this.config.translationObserver.subscribe(() => {
this.cd.markForCheck();
});
}
ngAfterViewInit() {
if (isPlatformBrowser(this.platformId)) {
if (this.mode === 'advanced') {
this.zone.runOutsideAngular(() => {
if (this.content) {
this.dragOverListener = this.renderer.listen(this.content.nativeElement, 'dragover', this.onDragOver.bind(this));
}
});
}
}
}
getTranslation(option: string) {
return this.config.getTranslation(option);
}
choose() {
this.advancedFileInput?.nativeElement.click();
}
onFileSelect(event: any) {
if (event.type !== 'drop' && this.isIE11() && this.duplicateIEEvent) {
this.duplicateIEEvent = false;
return;
}
this.msgs = [];
if (!this.multiple) {
this.files = [];
}
let files = event.dataTransfer ? event.dataTransfer.files : event.target.files;
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (!this.isFileSelected(file)) {
if (this.validate(file)) {
if (this.isImage(file)) {
file.objectURL = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(files[i]));
}
this.files.push(files[i]);
}
}
}
this.onSelect.emit({ originalEvent: event, files: files, currentFiles: this.files });
// this will check the fileLimit with the uploaded files
this.checkFileLimit(files);
if (this.hasFiles() && this.auto && !(this.mode === 'advanced') && !this.isFileLimitExceeded()) {
this.upload();
}
if (event.type !== 'drop' && this.isIE11()) {
this.clearIEInput();
} else {
this.clearInputElement();
}
}
isFileSelected(file: File): boolean {
for (let sFile of this.files) {
if (sFile.name + sFile.type + sFile.size === file.name + file.type + file.size) {
return true;
}
}
return false;
}
isIE11() {
if (isPlatformBrowser(this.platformId)) {
return !!(this.document.defaultView as any)['MSInputMethodContext'] && !!(this.document as any)['documentMode'];
}
}
validate(file: File): boolean {
this.msgs = this.msgs || [];
if (this.accept && !this.isFileTypeValid(file)) {
this.msgs.push({
severity: 'error',
summary: this.invalidFileTypeMessageSummary.replace('{0}', file.name),
detail: this.invalidFileTypeMessageDetail.replace('{0}', this.accept)
});
return false;
}
if (this.maxFileSize && file.size > this.maxFileSize) {
this.msgs.push({
severity: 'error',
summary: this.invalidFileSizeMessageSummary.replace('{0}', file.name),
detail: this.invalidFileSizeMessageDetail.replace('{0}', this.formatSize(this.maxFileSize))
});
return false;
}
return true;
}
private isFileTypeValid(file: File): boolean {
let acceptableTypes = this.accept?.split(',').map((type) => type.trim());
for (let type of acceptableTypes!) {
let acceptable = this.isWildcard(type) ? this.getTypeClass(file.type) === this.getTypeClass(type) : file.type == type || this.getFileExtension(file).toLowerCase() === type.toLowerCase();
if (acceptable) {
return true;
}
}
return false;
}
getTypeClass(fileType: string): string {
return fileType.substring(0, fileType.indexOf('/'));
}
isWildcard(fileType: string): boolean {
return fileType.indexOf('*') !== -1;
}
getFileExtension(file: File): string {
return '.' + file.name.split('.').pop();
}
isImage(file: File): boolean {
return /^image\//.test(file.type);
}
onImageLoad(img: any) {
window.URL.revokeObjectURL(img.src);
}
/**
* Uploads the selected files.
* @group Method
*/
upload() {
if (this.customUpload) {
if (this.fileLimit) {
this.uploadedFileCount += this.files.length;
}
this.uploadHandler.emit({
files: this.files
});
this.cd.markForCheck();
} else {
this.uploading = true;
this.msgs = [];
let formData = new FormData();
this.onBeforeUpload.emit({
formData: formData
});
for (let i = 0; i < this.files.length; i++) {
formData.append(this.name!, this.files[i], this.files[i].name);
}
this.http
.request(<string>this.method, this.url as string, {
body: formData,
headers: this.headers,
reportProgress: true,
observe: 'events',
withCredentials: this.withCredentials
})
.subscribe(
(event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Sent:
this.onSend.emit({
originalEvent: event,
formData: formData
});
break;
case HttpEventType.Response:
this.uploading = false;
this.progress = 0;
if (event['status'] >= 200 && event['status'] < 300) {
if (this.fileLimit) {
this.uploadedFileCount += this.files.length;
}
this.onUpload.emit({ originalEvent: event, files: this.files });
} else {
this.onError.emit({ files: this.files });
}
this.clear();
break;
case HttpEventType.UploadProgress: {
if (event['loaded']) {
this.progress = Math.round((event['loaded'] * 100) / event['total']!);
}
this.onProgress.emit({ originalEvent: event, progress: this.progress });
break;
}
}
this.cd.markForCheck();
},
(error: ErrorEvent) => {
this.uploading = false;
this.onError.emit({ files: this.files, error: error });
}
);
}
}
/**
* Clears the files list.
* @group Method
*/
clear() {
this.files = [];
this.uploadedFileCount = 0;
this.onClear.emit();
this.clearInputElement();
this.cd.markForCheck();
}
remove(event: Event, index: number) {
this.clearInputElement();
this.onRemove.emit({ originalEvent: event, file: this.files[index] });
this.files.splice(index, 1);
this.checkFileLimit(this.files);
}
isFileLimitExceeded() {
const isAutoMode = this.auto;
const totalFileCount = isAutoMode ? this.files.length : this.files.length + this.uploadedFileCount;
if (this.fileLimit && this.fileLimit <= totalFileCount && this.focus) {
this.focus = false;
}
return this.fileLimit && this.fileLimit < totalFileCount;
}
isChooseDisabled() {
if (this.auto) {
return this.fileLimit && this.fileLimit <= this.files.length;
} else {
return this.fileLimit && this.fileLimit <= this.files.length + this.uploadedFileCount;
}
}
checkFileLimit(files: File[]) {
this.msgs ??= [];
const hasExistingValidationMessages = this.msgs.length > 0 && this.fileLimit < files.length;
if (this.isFileLimitExceeded() || hasExistingValidationMessages) {
this.msgs.push({
severity: 'error',
summary: this.invalidFileLimitMessageSummary.replace('{0}', (this.fileLimit as number).toString()),
detail: this.invalidFileLimitMessageDetail.replace('{0}', (this.fileLimit as number).toString())
});
}
}
clearInputElement() {
if (this.advancedFileInput && this.advancedFileInput.nativeElement) {
this.advancedFileInput.nativeElement.value = '';
}
if (this.basicFileInput && this.basicFileInput.nativeElement) {
this.basicFileInput.nativeElement.value = '';
}
}
clearIEInput() {
if (this.advancedFileInput && this.advancedFileInput.nativeElement) {
this.duplicateIEEvent = true; //IE11 fix to prevent onFileChange trigger again
this.advancedFileInput.nativeElement.value = '';
}
}
hasFiles(): boolean {
return this.files && this.files.length > 0;
}
onDragEnter(e: DragEvent) {
if (!this.disabled) {
e.stopPropagation();
e.preventDefault();
}
}
onDragOver(e: DragEvent) {
if (!this.disabled) {
DomHandler.addClass(this.content?.nativeElement, 'p-fileupload-highlight');
this.dragHighlight = true;
e.stopPropagation();
e.preventDefault();
}
}
onDragLeave(event: DragEvent) {
if (!this.disabled) {
DomHandler.removeClass(this.content?.nativeElement, 'p-fileupload-highlight');
}
}
onDrop(event: any) {
if (!this.disabled) {
DomHandler.removeClass(this.content?.nativeElement, 'p-fileupload-highlight');
event.stopPropagation();
event.preventDefault();
let files = event.dataTransfer ? event.dataTransfer.files : event.target.files;
let allowDrop = this.multiple || (files && files.length === 1);
if (allowDrop) {
this.onFileSelect(event);
}
}
}
onFocus() {
this.focus = true;
}
onBlur() {
this.focus = false;
}
formatSize(bytes: number) {
const k = 1024;
const dm = 3;
const sizes = this.getTranslation(TranslationKeys.FILE_SIZE_TYPES);
if (bytes === 0) {
return `0 ${sizes[0]}`;
}
const i = Math.floor(Math.log(bytes) / Math.log(k));
const formattedSize = (bytes / Math.pow(k, i)).toFixed(dm);
return `${formattedSize} ${sizes[i]}`;
}
onBasicUploaderClick() {
if (this.hasFiles()) this.upload();
else this.basicFileInput?.nativeElement.click();
}
onBasicKeydown(event: KeyboardEvent) {
switch (event.code) {
case 'Space':
case 'Enter':
this.onBasicUploaderClick();
event.preventDefault();
break;
}
}
imageError(event: Event) {
this.onImageError.emit(event);
}
getBlockableElement(): HTMLElement {
return this.el.nativeElement.children[0];
}
get chooseButtonLabel(): string {
return this.chooseLabel || this.config.getTranslation(TranslationKeys.CHOOSE);
}
get uploadButtonLabel(): string {
return this.uploadLabel || this.config.getTranslation(TranslationKeys.UPLOAD);
}
get cancelButtonLabel(): string {
return this.cancelLabel || this.config.getTranslation(TranslationKeys.CANCEL);
}
ngOnDestroy() {
if (this.content && this.content.nativeElement) {
if (this.dragOverListener) {
this.dragOverListener();
this.dragOverListener = null;
}
}
if (this.translationSubscription) {
this.translationSubscription.unsubscribe();
}
}
}
@NgModule({
imports: [CommonModule, HttpClientModule, SharedModule, ButtonModule, ProgressBarModule, MessagesModule, RippleModule, PlusIcon, UploadIcon, TimesIcon],
exports: [FileUpload, SharedModule, ButtonModule, ProgressBarModule, MessagesModule],
declarations: [FileUpload]
})
export class FileUploadModule {}