Detect & Validate file types by their ‘magic numbers’ in React

Nir Almog
3 min readMay 10, 2023

--

Problem

Have you ever encountered the challenge of accurately identifying file types in your applications?
File validation & detection can be a complex task, especially when relying solely on file extensions. A simple file extension can easily be changed or spoofed, leading to potential security risks and compatibility issues. 😨😨

Solution

Using Magic Numbers’! 😎
What are they? From wikipedia:

A constant numerical or text value used to identify a file format or protocol; for files.

In other words, ‘magic numbers’ (known also as ‘file signatures’) are unique byte sequences found at the beginning of file contents. that provide crucial clues about the file’s type.

A list of all known ‘magic numbers’ can be found on wikipedia — List of file signatures or GCK’S Files Signatures table.

Detect & Validate with ‘file-type-checker’

With file-type-checker npm package, you can confidently detect & validate file types based on their ‘magic numbers’, enhancing the security and reliability of your applications.

This package checks a chunk of the first 64 bytes of the file by default (can be edited), covering most known ‘magic numbers’ positions.
This ensure an immediate response without unnecessary checks.

A simple usage of this package with React, is by using the FileReader API to read the file as an ArrayBuffer,allowing you to access its bytes

Validate file types in React

Suppose we want to only accept three input file types for images in our application: JPEG, PNG, and GIF:

import fileTypeChecker from "file-type-checker";

const handleFileInputChange = (event) => {
try {
const file = event.target.files[0];
const reader = new FileReader();
const types = ["jpeg", "png", "gif"];

reader.onload = () => {
const isImage= fileTypeChecker.validateFileType(reader.result, types);
console.log(isImage); // Returns true if the file is an image from the accepted list
};

reader.readAsArrayBuffer(file);
} catch (err) {
console.error("Error: ", err.message);
}
};

return (
<div>
<input type="file" onChange={handleFileInputChange} />
</div>
);

Parameters:

  • ‘reader.result’ — The input file represented as an ArrayBuffer.
  • ‘types’ — An array of string representing the accepted file types (can only include types from the package s supported files table).

By using the validateFileType method, we can check if the input file has the 'magic numbers' of one of our accepted types. If it does, the method will return a boolean value of true. Otherwise, it will return false.

Detect file types in React

Suppose we want to detect a simple PNG input file on our application and get its ‘magic numbers’ sequence along with some additional data:

import fileTypeChecker from "file-type-checker";

// Function to handle file input change
const handleFileInputChange = (event) => {
try {
const file = event.target.files[0];
const reader = new FileReader();

// When the file is loaded, detect its type
reader.onload = () => {
const detectedFile = fileTypeChecker.detectFile(reader.result);
console.log(detectedFile) >
{
extension: "png",
mimeType: "image/png",
description:
"PNG (Portable Network Graphics) is a lossless image compression format that supports a wide range of color depths and transparency and is widely used for high-quality graphics.",
signature: {
sequence: ["89", "50", "4e", "47", "d", "a", "1a", "a"],
},
};
};

// Use the FileReader API to read the file as an ArrayBuffer
reader.readAsArrayBuffer(file);
} catch (err) {
console.error("Error: ", err.message);
}
};

return (
<div>
<input type="file" onChange={handleFileInputChange} />
</div>
);

Parameters:

  • ‘reader.result’ —Represents the input file as an ArrayBuffer

By using the detectFile method allows us to detect the input file type based on its ‘magic numbers’ and retrieve information about the detected type.
The signature.sequence property represents the detected ‘magic numbers’.

Summary

In conclusion, using ‘magic numbers’ for file types detection & validation is a crucial feature for ensuring the security and integrity of your application.
The npm package file-type-checker will help you do it quickly and safely.

--

--