-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-to-base64.html
100 lines (90 loc) · 2.82 KB
/
file-to-base64.html
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
94
95
96
97
98
99
100
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="HandheldFriendly" content="true" />
<title>Artem Avramenko - Convert File to Base64 and Back</title>
<link rel="stylesheet" href="./sakura-earthly.css" />
<style>
input {width: 100% }
</style>
</head>
<body>
<section id="to-base64">
<h3>File to Base64:</h3>
<input type="file" />
<input type="text" readonly />
<button>copy</button><span id="copied-hint" style="visibility: hidden"> copied!</span>
</section>
<hr>
<section id="from-base64">
<h3>Base64 to File:</h3>
<input type="text" placeholder="Base64 text"/>
<div>
<a>Download</a>
</div>
</section>
<script>
// File to Base64
const fileInput = document.querySelector('#to-base64 input[type=file]');
const base64output = document.querySelector('#to-base64 input[type=text]');
const copyButton = document.querySelector('#to-base64 button');
const copiedHint = document.querySelector('#copied-hint');
fileInput.addEventListener('change', e => {
base64output.value = 'Loading...';
const reader = new FileReader();
reader.onload = e => {
try {
const data = new Uint8Array(e.target.result);
let s = '';
for (let d of data) {
s += String.fromCharCode(d);
}
base64output.value = btoa(s);
base64output.select();
} catch(e) {
base64output.value = e.toString();
}
}
try {
reader.readAsArrayBuffer(e.target.files[0]);
} catch(e) {
base64output.value = e.toString();
}
}, false);
if (!navigator.clipboard) {
copyButton.remove();
copiedHint.remove();
} else {
copyButton.addEventListener('click', e => {
const text = base64output.value;
navigator.clipboard.writeText(text);
copiedHint.style.visibility = 'visible';
setTimeout(() => copiedHint.style.visibility = 'hidden', 600);
});
}
// Base64 to file
const base64Input = document.querySelector('#from-base64 input');
const fileOutput = document.querySelector('#from-base64 a');
const signatures = [
['zip', 'application/x-zip-compressed', 'UEsDB'], // PK\x03\x04
['7z', 'application/x-7z-compressed', 'N3q8rycc'] // 7z\xBC\xAF\x27\x1C
]
setBase64 = base64 => {
fileOutput.download = 'download';
let mimeType = 'application/octet-stream';
for (let x of signatures) {
if (base64.startsWith(x[2])) {
fileOutput.download += '.' + x[0];
mimeType = x[1];
break;
}
}
fileOutput.href = `data:${mimeType};base64,${base64}`;
};
setBase64('');
base64Input.addEventListener('input', event => setBase64(event.target.value));
</script>
</body>
</html>