Created
July 24, 2022 09:21
-
-
Save semlinker/7bd11c41b18647f5057ee71bb58db782 to your computer and use it in GitHub Desktop.
File Type Detect Demo
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> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>File Type Detect Demo</title> | |
</head> | |
<body> | |
<div> | |
<input type="file" id="inputFile" accept="image/*" onchange="handleChange(event)"/> | |
<p id="realFileType"></p> | |
</div> | |
<script> | |
function check(headers) { | |
return (buffers,options={ | |
offset: 0 | |
})=>headers.every((header,index)=>header === buffers[options.offset + index]); | |
} | |
function readBuffer(file, start=0, end=2) { | |
return new Promise((resolve,reject)=>{ | |
const reader = new FileReader(); | |
reader.onload = ()=>{ | |
resolve(reader.result); | |
} | |
; | |
reader.onerror = reject; | |
reader.readAsArrayBuffer(file.slice(start, end)); | |
} | |
); | |
} | |
const isPNG = check([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); | |
const realFileElement = document.querySelector("#realFileType"); | |
async function handleChange(event) { | |
const file = event.target.files[0]; | |
const buffers = await readBuffer(file, 0, 8); | |
const uint8Array = new Uint8Array(buffers); | |
realFileElement.innerText = `The type of ${file.name} is:${isPNG(uint8Array) ? "image/png" : file.type}`; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment