function getMimeType(file) {
const reader = new FileReader();
reader.onloadend = function() {
const arr = (new Uint8Array(reader.result)).subarray(0, 4);
let header = "";
for(let i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
switch (header) {
case "89504e47":
return "image/png";
case "47494638":
return "image/gif";
case "25504446":
return "application/pdf";
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
return "image/jpeg";
default:
return "unknown";
}
};
reader.readAsArrayBuffer(file);
}
This function takes a file object as an argument and returns the actual MIME type of the file. It uses a FileReader object to read the content of the file and then checks the first few bytes of the file to determine its actual MIME type. Different file formats have different “magic numbers” at the beginning of the file, which can be used to identify the file format.
In the example code, we have included some common file formats and their corresponding magic numbers. You can add more formats and magic numbers to this function as needed.