Detect file mime type using magic numbers and JavaScript
The browser File API in the quite powerful, the requirement of modern website is not just text and images but also video, sound and other binary formats, this has led to an improved support for handling files directly in the browser.
In this article we’ll have a look of how to use the FileReader to read the first four bytes of a file to determine the mime type of the file. This will give us a more accurate way to tell the mime type, and not just examining the file extension, which is browser default behaviour.
What is magic numbers and how to use them
Magic numbers, or file signatures is a byte pattern inside a file that is used to determine which kind of file you are dealing with. In our example we are reading the first four bytes.
A constant numerical or text value used to identify a file format or protocol — Wikipedia
You can read more about file signatures at Wikipedia and Whatwg.
Why not use the file object type
The default browser file type implementation only uses the file extension to determine the file type, in most cases this works pretty well. It doesn’t work very well when the…