Skip to content

Instantly share code, notes, and snippets.

@kikill95
Created April 17, 2018 10:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kikill95/526f5888eb9970e0f3123b8a5a869028 to your computer and use it in GitHub Desktop.
Save kikill95/526f5888eb9970e0f3123b8a5a869028 to your computer and use it in GitHub Desktop.
Detect file mime type using magic numbers and JavaScript
<!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>
<p>You can read more about file signatures at Wikipedia and Whatwg.</p>
<p>https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern</p>
<p>https://en.wikipedia.org/wiki/List_of_file_signatures</p>
<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',
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>
Hex: <em>${file.hex}</em>
</div>`
})
container.innerHTML = uploadedFiles.join('')
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment