-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileReader.js
70 lines (64 loc) · 1.88 KB
/
FileReader.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
import Button from "./Button.js"
import Component from "./Component.js"
import EventHandler from "./EventHandler.js"
import Input from "./Input.js"
export default class MyFileReader extends EventHandler {
static events = {
load: "load",
}
static readerTypes = {
binary:"binary",arrayBuffer:"arrayBuffer",url:"url",text:"text"
}
constructor() {
super()
this.setReaderType(MyFileReader.readerTypes.text)
/** @type {Input}*/
this.input = new Input()
.setType("file")
.addAttributes({ accept: ".txt" })
.build()
this.button = new Button()
this.input.addEventListener(Input.events.change, (e) => {
let reader = new FileReader()
reader.onload = (event) => {
const res = {
result :event.target.result,
file: this.input.getFile()
}
this.dispatchEvent(MyFileReader.events.load,res )
this.button.dispatchEvent(MyFileReader.events.load, res)
}
switch (this.readType){
case MyFileReader.readerTypes.arrayBuffer:
reader.readAsArrayBuffer(this.input.getFile())
break
case MyFileReader.readerTypes.url:
reader.readAsDataURL(this.input.getFile())
break
case MyFileReader.readerTypes.text:
reader.readAsText(this.input.getFile())
break
case MyFileReader.readerTypes.binary:
reader.readAsBinaryString(this.input.getFile())
break
}
})
this.button.addEventListener(Component.events.mousedown, () => {
this.clickUpload()
})
}
setFilesAccept(files) {
this.input.addAttributes({ accept: files })
return this
}
setReaderType(type){
this.readType = type
return this
}
clickUpload(){
this.input.getContainer().click()
}
getButton() {
return this.button
}
}