Curious what the best way is in Java to get the mime-type of a file. It should actually inspect the file because filenames aren't an accurate indicator.
Currently I'm using the following which seems to be very hit or miss
is = new BufferedInputStream(new FileInputStream(fileName)); String mimeType = URLConnection.guessContentTypeFromStream(is); if(mimeType == null) { throw new IOException("can't get mime type of image"); }
To fetch mime type for a file, you would simply use Files and do this in your code: Files. probeContentType(Paths. get("either file name or full path goes here"));
A MIME type has two parts: a type and a subtype. They are separated by a slash (/). For example, the MIME type for Microsoft Word files is application and the subtype is msword. Together, the complete MIME type is application/msword.
Multiple MIME types can use one extension. For example, if your organization uses multiple versions of a program, you can define a MIME type for each version; however, file names of all versions use the same extension.
MIME types also can not be misleading. MIME types are the authoritative declaration of what something is. If it's not that, then there is nothing misleading, it's simply invalid. Framing this as "MIME spoofing" is about as sensible as calling a buffer overflow in some font renderer "machine code spoofing".
The URLConnection#guessContentTypeFromStream()
or ...FromName()
is indeed the best what you can get in the standard Java SE API. There are however 3rd party libraries like jMimeMagic which does its work better than URLConnection#guessXXX()
methods.
String mimeType = Magic.getMagicMatch(file, false).getMimeType();
This supports a more wide range of mime types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With