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...
  • Shubhashish Bhowmik

    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 :)

    • http://www.pakzilla.com Tahir Akram

      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 :)  

  • Michael Safyan

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

    • http://www.pakzilla.com Tahir Akram

      I have made these checks as part of my validation methods in struts2. Might be I should shift it to interceptors. 

  • Guest

    In JDK7 you can use Files.probeContentType.

    • http://www.pakzilla.com Tahir Akram

      Thanks for the tip.

    • http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html Rajv Kaurya

      Thanks Tahir and Guest for pointing out two quick tips to find out mime type. specially java7 one which is lost in other popular features like ARM  and fork join framework, is great because you don’t need to include another library

  • http://www.pakzilla.com Tahir Akram

    Just updated a dependency that is required to run JMimeMagic. That is Jakarat ORO. 

  • http://www.pakzilla.com Tahir Akram

    Jakarta ORO is a required dependency for JMimeMagic. Post updated.

  • Tinh Truong

    I used to use http://sourceforge.net/projects/mime-util/ to solve this problem.