-
-
Save Shinsekai7/f352ae03feb4611e9d629e2386043c98 to your computer and use it in GitHub Desktop.
Use filereader to extract mimetype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<title>Filereader</title> | |
<style> | |
div { | |
font-family: "Helvetica Neue"; | |
line-height:22px; | |
font-size:15px; | |
margin:10px 0; | |
color: #333; | |
} | |
em { | |
padding: 2px 4px; | |
background-color: #efefef; | |
font-style: normal; | |
} | |
</style> | |
</head> | |
<body> | |
<input type="file" id="file-selector"> | |
<div id="files"></div> | |
<script> | |
const uploads = [] | |
const fileSelector = document.getElementById('file-selector') | |
fileSelector.addEventListener('change', (event) => { | |
console.time('FileOpen') | |
const file = event.target.files[0] | |
const filereader = new FileReader() | |
filereader.onloadend = function(evt) { | |
if (evt.target.readyState === FileReader.DONE) { | |
const uint = new Uint8Array(evt.target.result) | |
let bytes = [] | |
uint.forEach((byte) => { | |
bytes.push(byte.toString(16)) | |
}) | |
const hex = bytes.join('').toUpperCase() | |
uploads.push({ | |
filename: file.name, | |
filetype: file.type ? file.type : 'Unknown/Extension missing', | |
binaryFileType: getMimetype(hex), | |
hex: hex | |
}) | |
render() | |
} | |
console.timeEnd('FileOpen') | |
} | |
const blob = file.slice(0, 4); | |
filereader.readAsArrayBuffer(blob); | |
}) | |
const render = () => { | |
const container = document.getElementById('files') | |
const uploadedFiles = uploads.map((file) => { | |
return `<div> | |
<strong>${file.filename}</strong><br> | |
Filetype from file object: ${file.filetype}<br> | |
Filetype from binary: ${file.binaryFileType}<br> | |
Hex: <em>${file.hex}</em> | |
</div>` | |
}) | |
container.innerHTML = uploadedFiles.join('') | |
} | |
const getMimetype = (signature) => { | |
switch (signature) { | |
case '89504E47': | |
return 'image/png' | |
case '47494638': | |
return 'image/gif' | |
case '25504446': | |
return 'application/pdf' | |
case 'FFD8FFDB': | |
case 'FFD8FFE0': | |
return 'image/jpeg' | |
case '504B0304': | |
return 'application/zip' | |
default: | |
return 'Unknown filetype' | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment