|
| 1 | +import { Directive, ElementRef, EventEmitter, Input, Output, OnInit, OnDestroy } from '@angular/core'; |
| 2 | + |
| 3 | +@Directive({ |
| 4 | + selector: '[fileToBase64]' |
| 5 | +}) |
| 6 | +export class FctrlxFileToBase64Directive implements OnInit, OnDestroy { |
| 7 | + |
| 8 | + @Input() files: any; |
| 9 | + @Input() type: string; |
| 10 | + @Input() multiple: any; |
| 11 | + |
| 12 | + @Output() filesChange: EventEmitter<any> = new EventEmitter(); |
| 13 | + |
| 14 | + private readonly TYPE_FILE: string = 'file'; |
| 15 | + |
| 16 | + private reader: FileReader = new FileReader(); |
| 17 | + private converted: any = []; |
| 18 | + private currentIndex: number = 0; |
| 19 | + |
| 20 | + constructor(private element: ElementRef) {} |
| 21 | + |
| 22 | + ngOnInit(): void { |
| 23 | + if(this.type === this.TYPE_FILE) { |
| 24 | + this.element.nativeElement.addEventListener('change', this.filesChanged.bind(this), false); |
| 25 | + |
| 26 | + this.reader.onload = (file) => { |
| 27 | + this.readFile(file) |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + get isMultiple(): boolean { |
| 33 | + return !(typeof this.multiple === 'undefined'); |
| 34 | + } |
| 35 | + |
| 36 | + filesChanged(event) { |
| 37 | + let files = event.target.files; |
| 38 | + |
| 39 | + this.converted = []; |
| 40 | + this.currentIndex = 0; |
| 41 | + |
| 42 | + Object.keys(files).forEach((key) => { |
| 43 | + const { name, size, type, base64 } = files[key]; |
| 44 | + |
| 45 | + this.converted.push({ |
| 46 | + name, |
| 47 | + size, |
| 48 | + type, |
| 49 | + base64 |
| 50 | + }); |
| 51 | + |
| 52 | + this.reader.readAsDataURL(files[key]); |
| 53 | + }); |
| 54 | + |
| 55 | + this.filesChange.next(this.isMultiple ? this.converted : this.converted[0]); |
| 56 | + } |
| 57 | + |
| 58 | + readFile(file) { |
| 59 | + this.converted[this.currentIndex].base64 = file.target.result; |
| 60 | + } |
| 61 | + |
| 62 | + ngOnDestroy(): void { |
| 63 | + this.element.nativeElement.removeEventListener('change', this.filesChanged.bind(this), false); |
| 64 | + this.reader.onload = null; |
| 65 | + } |
| 66 | +} |
0 commit comments