How to find mime type of a file in Java

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.

Related Posts Plugin for WordPress, Blogger...

10 thoughts on “How to find mime type of a file in Java

  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 🙂

    • 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

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