Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if the file format is different with the file name extension in Python, Javascript?

I have an uploader which has file format validation (only some video formats can be uploaded).

However users can simply change the original file name extension and pass the validation (e.g. rename file.pdf to file.mov and upload)!

Now I need to check and validate if the file format matches the file extension or not. The backend is Python (Django), but I am not sure if this can be done via Payton, Javascript or any other solution.

like image 235
Carmijoon Avatar asked Apr 28 '26 10:04

Carmijoon


1 Answers

In python you can use python-magic

Quote from the Readme:

python-magic is a python interface to the libmagic file type identification library. libmagic identifies file types by checking their headers according to a predefined list of file types.

It analyses the file header instead of using only the file extension to recognise the file type.

The usage is simple:

>>> import magic
>>> magic.from_file('renamed.pdf')
'ISO Media, Apple QuickTime movie'
# More handy
>>> magic.from_file('renamed.pdf', mime=True)
'video/quicktime'
like image 108
Mathias Avatar answered May 01 '26 00:05

Mathias