-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.reader.component.ts
93 lines (79 loc) · 2.5 KB
/
file.reader.component.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
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'filereader',
template: `
<style>
#file-input {
cursor: pointer;
outline: none;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
overflow: hidden;
filter: alpha(opacity=0);
/* IE < 9 */
opacity: 0;
}
.input-label {
cursor: pointer;
position: relative;
display: inline-block;
}
</style>
<div>
<label for="file-input" class="input-label">
<button style="width: 160px" class="btn btn-primary" (click)="onClickHandle()" [ngClass]="{'disabled': !enabled}">
<span class="glyphicon glyphicon-{{image}}" aria-hidden="true"></span> {{caption}}
</button>
<input type="file" id="file-input" (change)="changeListener($event)">
</label>
</div>
`
})
export class FileReaderComponent {
@Input() enabled: boolean = true;
@Input() caption: string = "Load File";
/**
* readMode:
* text: read the contents of the file as a text string.
* data: the data as a URL representing the file's data as a base64 encoded string (like images)
* array: the result attribute contains an ArrayBuffer representing the file's data.
*/
@Input() readMode: string = "text";
@Input() image: string = "folder-open";
@Input() onValidate: (value: File) => boolean;
@Output() onCallback: EventEmitter<any> = new EventEmitter();
constructor() { }
changeListener($event: any) {
let self = this;
let file: File = $event.target.files[0];
let myReader: FileReader = new FileReader();
if (this.doValidate(file)) {
if (this.readMode == "array")
myReader.readAsArrayBuffer(file)
else if (this.readMode == "data")
myReader.readAsDataURL(file);
else // text
myReader.readAsText(file);
myReader.onloadend = function (e) {
self.onReadDone(myReader.result);
};
}
}
onReadDone(text: any) {
this.onCallback.emit(text);
}
onClickHandle() {
let file = document.getElementById('file-input');
file.click();
}
doValidate(file: File) {
let value: boolean = false;
if (this.onValidate != undefined) {
value = this.onValidate(file);
}
return value;
}
}