Created
June 24, 2024 05:34
-
-
Save r1d3rzz/5e751c4578f4aa5fac0196eb28bb46c1 to your computer and use it in GitHub Desktop.
File Type Filter WIth JS
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 checkFileExtension(file, ...allowFileTypes) { | |
const allowedExtensions = allowFileTypes; // List allowed extensions | |
const fileExtension = file.name.split('.').pop().toLowerCase(); | |
return allowedExtensions.includes(fileExtension); | |
} | |
function checkContentType(file) { | |
const allowedTypes = ['image/jpeg', 'image/png', 'application/zip', 'application/pdf']; // List allowed MIME types | |
return allowedTypes.includes(file.type); | |
} | |
function checkMagicNumber(file) { | |
return new Promise((resolve, reject) => { | |
const reader = new FileReader(); | |
reader.onload = function (e) { | |
const arrayBuffer = e.target.result; | |
const uint8Array = new Uint8Array(arrayBuffer); | |
// JPEG files start with 0xFFD8 | |
// PNG files start with 0x89504E47 | |
// ZIP files start with 0x504B0304 | |
// PDF files start with 0x25504446 | |
const jpegMagicNumber = uint8Array[0] === 0xFF && uint8Array[1] === 0xD8; | |
const pngMagicNumber = uint8Array[0] === 0x89 && uint8Array[1] === 0x50 && uint8Array[2] === 0x4E && uint8Array[3] === 0x47; | |
const zipMagicNumber = uint8Array[0] === 0x50 && uint8Array[1] === 0x4B && uint8Array[2] === 0x03 && uint8Array[3] === 0x04; | |
const pdfMagicNumber = uint8Array[0] === 0x25 && uint8Array[1] === 0x50 && uint8Array[2] === 0x44 && uint8Array[3] === 0x46; | |
if (jpegMagicNumber || pngMagicNumber || zipMagicNumber || pdfMagicNumber) { | |
resolve(true); | |
} else { | |
resolve(false); | |
} | |
}; | |
reader.onerror = function () { | |
reject(new Error("Error reading file")); | |
}; | |
reader.readAsArrayBuffer(file.slice(0, 4)); // Read the first 4 bytes | |
}); | |
} | |
// Usage | |
// ------- | |
$('#input').on('change', async function(){ | |
let file = ....; | |
const isValidExtension = checkFileExtension(file, 'jpg', 'png', 'jpeg'); | |
const isValidContentType = checkContentType(file); | |
const isValidMagicNumber = await checkMagicNumber(file); | |
if (isValidExtension && isValidContentType && isValidMagicNumber) { | |
alert("Is Valid"); | |
} else { | |
alert("Is NOT Valid"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment