Last active
December 17, 2021 15:06
-
-
Save cihad/f405b94633aa4f271d3510af3dfa75dd to your computer and use it in GitHub Desktop.
check file media type (mime) with javascript
This file contains 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
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 | |
} |
This file contains 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
<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