DEV Community

Cover image for How to detect file type in JavaScript without checking its file object type?
Luca
Luca

Posted on

How to detect file type in JavaScript without checking its file object type?

Usually when we want to check the type for a file that we have to upload we look for its MIME type in the file object.

MIME type is a standard that indicates the nature and format of a file, here you can get a list of the most common, there are really many of them.

But.. What if the file for some reasons doesn't has an extension or have a wrong extension assigned? 🤔

Luckily the magic numbers come to our aid.

Magic numbers are a byte pattern inside a file that is used to determine which is the type of the file.

Or, more properly, from Wikipedia:

Magic numbers implement strongly typed data and are a form of in-band signaling to the controlling program that reads the data type(s) at program run-time. Many files have such constants that identify the contained data

For have an example of how to implement magic numbers "by hand" with the FileReader API I strongly recommend reading this article by Andreas Kihlberg.

I want instead focus on the file-type library. This library applies the magic numbers approach to the ArrayBuffer of the file for detecting its type. It works with a large amount of different file types.

Unfortunately some file types, especially plain-text files, are harder to spot by this method and if you want to check the type you have to use a parser for every kind of file you have to consider.
For example if you want to spot SVG you can use is-svg library from NPM.

I've created a Sandbox that use the file-type library which you can play around 👇

👋 See you in the next article!

Learn more

Discussion (0)