-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileReader.js
55 lines (54 loc) · 1.89 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
function addFileCollect(input, output) {
addFileReader(input, output);
addDrag(input, output);
}
/* A simple registration function to attach a file choice.reader to a textarea */
function addFileReader(input, output) {
const fileX = document.getElementById(input);
const out = document.getElementById(output);
const fileName = document.getElementById(input + "Name");
fileX.addEventListener("change", () => {
const[file] = fileX.files;
fileX.value = ""; /* Forces a subsequent read if no change in file chosen */
if (file) {
fileName.textContent = file.name;
const reader = new FileReader();
reader.addEventListener("load", () => {
out.value = reader.result;
});
reader.readAsText(file);
} else {
fileName.textContent = "";
}
})
}
function addDrag(input, output) {
const fileName = document.getElementById(input + "Name");
const out = document.getElementById(output)
out.addEventListener("dragenter", (event) => {
out.style.background = "lavenderblush";
const img = new Image();
img.src = "example.png";
event.dataTransfer.setDragImage(img, 20, 20);
event.preventDefault();
});
out.addEventListener("dragleave", (event) => {
out.style.background = "white";
event.preventDefault();
});
out.addEventListener("drop", (event) => {[...event.dataTransfer.items].forEach((item, i) => {
// If dropped items aren't files, reject them
if (item.kind === 'file') {
const file = item.getAsFile();
fileName.textContent = file.name;
const reader = new FileReader();
reader.addEventListener("load", () => {
out.value = reader.result;
});
reader.readAsText(file,'UTF-8');
}
});
out.style.background = "white";
event.preventDefault();
});
}