Skip to content

Instantly share code, notes, and snippets.

@cihad
Last active December 17, 2021 15:06
Show Gist options
  • Save cihad/f405b94633aa4f271d3510af3dfa75dd to your computer and use it in GitHub Desktop.
Save cihad/f405b94633aa4f271d3510af3dfa75dd to your computer and use it in GitHub Desktop.
check file media type (mime) with javascript
function readBlob(blob) {
return new Promise((res, rej) => {
const reader = new FileReader()
reader.onloadend = function() {
res(reader.result)
}
reader.onerror = rej
reader.readAsDataURL(blob)
})
}
async function getMediaType(blob) {
if (blob.type) return blob.type
blob = blob.slice(0, 4)
const data = await readBlob(blob)
const [,type] = data.match(/^data:(.+);/)
return type
}
<input type="file" id="fileInp" />
<script>
fileInp.addEventListener("change", async (event) => {
const [fileBlob] = event.target.files
console.log(await getMediaType(fileBlob))
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment