I was just wondering how most people fetch a mime type from a file in Java? So far I've tried two utils: JMimeMagic
& Mime-Util
.
The first gave me memory exceptions, the second doesn't close its streams off properly. I was just wondering if anyone else had a method/library that they used and worked correctly?
It is better to use two layer validation for files upload.
First you can check for the mimeType and validate it.
Second you should look to convert the first 4 bytes of your file to hexadecimal and then compare it with the magic numbers. Then it will be a really secure way to check for file validations.
if you work on linux OS ,there is a command line
file --mimetype
:Then
Apache Tika offers in tika-core a mime type detection based based on magic markers in the stream prefix.
tika-core
does not fetch other dependencies, which makes it as lightweight as the currently unmaintained Mime Type Detection Utility.Simple code example (Java 7), using the variables
theInputStream
andtheFileName
Please note that MediaType.detect(...) cannot be used directly (TIKA-1120). More hints are provided at https://tika.apache.org/0.10/detection.html.
From roseindia:
If you're an Android developer, you can use a utility class
android.webkit.MimeTypeMap
which maps MIME-types to file extensions and vice versa.Following code snippet may help you.
After trying various other libraries I settled with mime-util.