Skip to content

Instantly share code, notes, and snippets.

@abrarfahad
Forked from GiantZOC/MimeTypeVerification.js
Created March 27, 2023 04:43
Show Gist options
  • Save abrarfahad/9eda282d5a0dc1e24f7134fce1db09d1 to your computer and use it in GitHub Desktop.
Save abrarfahad/9eda282d5a0dc1e24f7134fce1db09d1 to your computer and use it in GitHub Desktop.
Check the header to see the file type
//https://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload/29672957#29672957
// Return the first few bytes of the file as a hex string
function getBLOBFileHeader(url, blob, callback) {
var fileReader = new FileReader();
fileReader.onloadend = function (e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += pad(arr[i].toString(16), 2);
}
callback(url, header);
};
fileReader.readAsArrayBuffer(blob);
}
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function headerCallback(url, headerString) {
printHeaderInfo(url, headerString);
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback);
}
// Add more from http://en.wikipedia.org/wiki/List_of_file_signatures
function mimeType(headerString) {
switch (headerString.toLowerCase()) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
type = "jpg"
break;
case "ffd8ffe1":
type = "jpg"
break;
case "ffd8ffdb":
type = "jpg"
break;
case "ffd8ffe2":
type = "image/jpeg";
break;
case "25504446":
type = "pdf";
break;
case "7b5c7274": //6631
type = "rtf";
break;
case "504b0304":
type = "zip archive (Office)";
break;
case "504b0506":
type = "zip archive empty";
break;
case "504b0708":
type = "zip archive spanned";
break;
case "49492a00":
type = "TIF (little endian format)";
break;
case "4d4d002a":
type = "TIF (big endian format)";
break;
case "d0cf11e0": //a1b11ae1
type = "Old Office Format";
break;
default:
type = "Unsupported";
break;
}
return type;
}
function printHeaderInfo(url, headerString) {
console.log("File Type: " + mimeType(headerString));
}
// Check for FileReader support
if (window.FileReader && window.Blob) {
/* Handle local files */
$("input").on('change', function (event) {
var file = event.target.files[0];
if (file.size >= 100 * 1024 * 1024) {
alert("File size must be at most 100MB");
return;
}
remoteCallback(escape(file.name), file);
});
} else {
// File and Blob are not supported
alert("Your browser is not supported");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment