I want to get the extension of uploaded file

I want to get the extension of uploaded file like( .txt, mp4, wav, .ts, .pdf, .doc, .csv, xlsx, … etc).
I want that I should have a script of library which could get me the extension of the uploaded file.
I am not using split() function, because there can be some files whose extension is not in their name, so for those we can’t get the extension using the split function.

Have you tried os.path.splitext?

2 Likes

Actually, I don’t want to use splitext(), because there are some files which doesn’t have extension in their name. And I want to check the file dynamically(its content), something like: magic library.

This makes things a lot harder, you need to check for any headers that might indicate what type of file it is, AFAIK not all files have a specific header identifying themselves.

For example, the header for a jpeg file is FF D8 FF.

This is also what libmagic does btw :sweat_smile:

2 Likes

You should also keep in mind that the file type is just a suggestion: the bytes are what they are, and you can try to interpret them many different ways - you just won’t always get a sensible result. But then, someone can paint random noise and call it a PNG, too.

And then, the file extension (if there is one) can just lie. I can take a compiled application and rename it with a .txt extension. What happens will depend on both the operating system and how the user tries to “open” it.

If you want to do something different with the uploaded file according to its “type”, then you’ll have to accept some guesswork.

If you want to protect users who download the file… good luck.

3 Likes

Thanks guys for your help.