Check uploaded file MIME type with JMimeMagic

October 24, 2007 at 7:44 pm | In IT Security, Java, Programming | 2 Comments

Does your web application allow users to upload file?

If so, it is important that you check the MIME type of the file instead of just checking that it is an acceptable file extension.

Let’s say you allow user to upload a zip file and it gets extracted at the server by running it.

Something bad could really happen if it happens that the .zip file is actually a .exe file being renamed to .zip

Some email servers will automatically remove .zip, .exe, .bat, .cmd files in email attachments for security or anti-virus reasons. Some will also check MIME type so that you cannot fool it into believing the file is clean.

So what is the best and easiest way, if you’re doing a java application to check MIME type?

Solution : 

1) Keep checking file extension.

2) Check the file with JMimeMagic

You can download it at SourceForge.net

If you would like to check API before putting your foot into it:

http://jmimemagic.sourceforge.net/apidocs/index.html

Generally, all it takes for you to use it is

http://jmimemagic.sourceforge.net/apidocs/net/sf/jmimemagic/Magic.html#getMagicMatch(byte[])[])

The very few lines of code needed :

 logger.debug("Checking magic content");
 Magic parser = new Magic() ;
 MagicMatch match;
 match = parser.getMagicMatch(photoFile.getFileData());
 logger.debug("Actual file mimetype=" + match.getMimeType()) ;

2 Comments »

RSS feed for comments on this post. TrackBack URI

  1. Have you tried mime-utils. I was searching for such a MIME Type detector and found jmimemagic and mime-utils. I think I’ll stop on mime-utils at least it’s well documented. Check it out http://www.medsea.eu/mime-util

    • JMimeMagic wasn’t able to discover the mime type “image/x-ms-bmp” of a file. Mime-utils on the other hand worked without a problem.


Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.