-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
69 lines (59 loc) · 2.35 KB
/
script.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
import { HuffmanCoder } from './huffman.js';
onload = function () {
// Get reference to elements
const treearea = document.getElementById('treearea');
const encode = document.getElementById('encode');
const decode = document.getElementById('decode');
const temptext = document.getElementById('temptext');
const upload = document.getElementById('uploadedFile');
const coder = new HuffmanCoder();
upload.addEventListener('change',()=>{ alert("File uploaded") });
encode.onclick = function () {
const uploadedFile = upload.files[0];
if(uploadedFile===undefined){
alert("No file uploaded !");
return;
}
const fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
const text = fileLoadedEvent.target.result;
if(text.length===0){
alert("Text can not be empty ! Upload another file !");
return;
}
let [encoded, tree_structure, info] = coder.encode(text);
downloadFile(uploadedFile.name.split('.')[0] +'_encoded.txt', encoded);
treearea.innerText = tree_structure;
treearea.style.marginTop = '2000px';
temptext.innerText = info;
};
fileReader.readAsText(uploadedFile, "UTF-8");
};
decode.onclick = function () {
const uploadedFile = upload.files[0];
if(uploadedFile===undefined){
alert("No file uploaded !");
return;
}
const fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
const text = fileLoadedEvent.target.result;
if(text.length===0){
alert("Text can not be empty ! Upload another file !");
return;
}
let [decoded, tree_structure, info] = coder.decode(text);
downloadFile(uploadedFile.name.split('.')[0] +'_decoded.txt', decoded);
treearea.innerText = tree_structure;
treearea.style.marginTop = '2000px';
temptext.innerText = info;
};
fileReader.readAsText(uploadedFile, "UTF-8");
};
};
function downloadFile(fileName, data){
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent(data);
a.download = fileName;
a.click();
}