Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a file's Media Type (MIME type)?

Tags:

java

mime

How do you get a Media Type (MIME type) from a file using Java? So far I've tried JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.

How would you probe the file to determine its actual type (not merely based on the extension)?

like image 371
Lee Theobald Avatar asked Sep 09 '08 09:09

Lee Theobald


People also ask

How do I find MIME type?

string mimeType = MimeMapping. GetMimeMapping(fileName); If you need to add custom mappings you probably can use reflection to add mappings to the BCL MimeMapping class, it uses a custom dictionary that exposes this method, so you should invoke the following to add mappings (never tested tho, but should prob. work).

What is a file's MIME type?

A multipurpose internet mail extension, or MIME type, is an internet standard that describes the contents of internet files based on their natures and formats. This cataloging helps the browser open the file with the appropriate extension or plugin.

How do I download a MIME file?

Tap on the "mime-attachment" that will open to display the text of the mail body with below the pdf / word files with as an indication "Tap to Download".

How do I fix MIME type error?

To Solve MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled ErrorJust make Sure Your File name and the name You are Using in Link Tag Both Are Same. For Example my File name is style. css Then My Link tag is Something like this:<link rel=”stylesheet” href=”style.


2 Answers

In Java 7 you can now just use Files.probeContentType(path).

like image 110
Chris Mowforth Avatar answered Sep 19 '22 06:09

Chris Mowforth


Unfortunately,

mimeType = file.toURL().openConnection().getContentType(); 

does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.

However, you have this:

mimeType= URLConnection.guessContentTypeFromName(file.getName()); 

and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content

InputStream is = new BufferedInputStream(new FileInputStream(file)); mimeType = URLConnection.guessContentTypeFromStream(is);  //...close stream 

However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).

like image 38
Joshua Fox Avatar answered Sep 21 '22 06:09

Joshua Fox