Search code examples
javascriptfile-typemagic-numbers

Determine filetype by magic number


I had to check filetype in file uploader to determine if file was image (jpg, png) and I decided to do it by reading file's magic number (4 first bytes) with FileReader but I have some doubts about this method:

  1. Is this method safe? Is there a way to upload non jpg file as jpg with this method?

  2. I've seen filetypes with different magic numbers size like 2, 4, 6 bytes... So If I had to make a generic method to determine not just image filetype but the others as well, I would have to read the maximum amount of bytes (to determine largest magic number) from the file, right?


Solution

    1. It's not safe. Problem is not only in magic numbers but already in that you try to validate it on client side. Form can be uploaded directly from a script bypassing your client side validation. Correct way to do it is to validate everything on server side using proven techniques.

    2. Right. Different file formats have different magic numbers on different offsets. But still if you care about security - dont trust anything.