check a file's header to approve or deny a file type in javascript

You can use the File API in JavaScript to read the file's header and check if it matches an expected value to approve or deny a file type. Here's an example:

index.tsx
function checkFileType(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);
        }

        // Compare the file header with the expected header
        if (header === "89504e47") { // Expected header for PNG files
            console.log("File type approved: PNG");
        } else {
            console.log("File type denied. Unsupported file type.");
        }
    };

    reader.readAsArrayBuffer(file);
}

// Example usage
const fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change", function(e) {
    const file = e.target.files[0];
    checkFileType(file);
});
813 chars
28 lines

In this example, we read the first 4 bytes of the file (commonly used for file signatures) and convert them to a hexadecimal string to compare with expected headers. You can change the expected header value in the comparison based on the file types you want to approve or deny.

Remember that this is a basic example. For a more comprehensive approach, you should consider checking more bytes from the file and compare with a broader range of file types.

related categories

gistlibby LogSnag