How to find mime type of a file in Java

person sticking a post it on a white board with the words how to written on it

Validating a file when it is getting uploaded in the system is some time very necessary. We can check the extension of the file, but what if user has changed the extension to crack the system. So the best way is to find the mime type. There are multiple libraries that you can use to get the mime type of a file. Java 6 IO APIs can’t do that. I used JMimeMagic for this. Following is a code snippet to get the mime type of a file.

MagicMatch match = Magic.getMagicMatch(getPromotionOptIn().getUpload(),false);
String mimeType = match.getMimeType();

You can download JMimeMagic lib from here.

JMimeMagic requires a dependency, that is Jakarata ORO. Jar can be downloaded from Apache archives.

You May Also Like

10 Comments

  1. Hi

    First of all thanks for sharing a good piece of information.

    Quite a year back i have faced a problem regarding finding the right mime type of a file. At that point of time i have used javax.activation.MimetypesFileTypeMap. Although i dont know whether solution is a perfect one or not but solves my problem.

    thanks 🙂

    1. Shubhashish! 
      Before using JMimeMagic, I was also thinking to use the Java Activation Framework. But the problem was, for every file upload it was giving me application/octet-stream so that does not work for me. And I found JMimeMagic. That solves my problem. You welcome 🙂 

  2. Finding the right mime type is useful for interpreting the file correctly, but should not be relied on for security validation.

Leave a Reply to Tahir Akram Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.