
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.
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 🙂
Finding the right mime type is useful for interpreting the file correctly, but should not be relied on for security validation.
I have made these checks as part of my validation methods in struts2. Might be I should shift it to interceptors.
In JDK7 you can use Files.probeContentType.
Thanks for the tip.
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
Just updated a dependency that is required to run JMimeMagic. That is Jakarat ORO.
Jakarta ORO is a required dependency for JMimeMagic. Post updated.
I used to use http://sourceforge.net/projects/mime-util/ to solve this problem.