After uploading a file in my application, I need to verify the file type by checking both the extension and including a magic bytes check. To accomplish this, I found a helpful article at:
Below is the code for my verification method:
checkFileTypeViaMagicByte(file):boolean {
const filereader = new FileReader();
const blob = file.slice(0, 4);
filereader.readAsArrayBuffer(blob);
filereader.onloadend= (evt) => {
if (evt.target.readyState === FileReader.DONE) {
// @ts-ignore
const uint = new Uint8Array(evt.target.result);
let bytes = []
uint.forEach((byte) => {
bytes.push(byte.toString(16))
})
const hex = bytes.join('').toUpperCase();
console.log("SIGNATURE: " + hex);
switch (hex) {
case '89504E47': //image/png
return true;
case '25504446'://application/pdf
console.log("PDF case");
return true;
case 'FFD8FFDB'://image/jpeg
case 'FFD8FFE0':
return true;
default:
return false;
}
};
};
return false;
}
The challenge I'm facing is that FileReader operates asynchronously and my method always returns false. Since I have multiple methods performing checks like allowed filenames and file sizes, I need to address this issue within a method. How can I resolve this problem?