Determine MIME type in Java

In this article we will see how to determine the MIME type of a file in Java.

Overview

A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) is a standard that indicates the nature and format of a document, file, or assortment of bytes. It is defined and standardized in IETF’s RFC 6838.

Browsers use the MIME type, not the file extension, to determine how to process a URL, so it’s important that web servers send the correct MIME type in the response’s Content-Type header. If this is not correctly configured, browsers are likely to misinterpret the contents of files and sites will not work correctly, and downloaded files may be mishandled.

Code

We will make use of MimeUtil. Add the below dependencies in you pom.xml:

<dependency>
    <groupId>eu.medsea.mimeutil</groupId>
    <artifactId>mime-util</artifactId>
    <version>2.1.3</version>
</dependency>

We need to register the Mime detector as well:

static {
 MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
}

The below method will get the MIME type from the content which is passed as a byte array:

public static String getMimeType(byte[] content) {
    final Collection mimeTypes = MimeUtil.getMimeTypes(content);
    return MimeUtil.getFirstMimeType(mimeTypes.toString()).toString();
}

The full source code can be found at java-mime-type

Test

Below is the code snippet for the test:

@Test
public void testGetMimeType_jpeg() throws IOException {
    final byte[] bytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("jpeg.jpeg"));
    final String mimeType = MimeTypeDeterminer.getMimeType(bytes);
    assertEquals("image/jpeg", mimeType);
}

@Test
public void testGetMimeType_png() throws IOException {
    final byte[] bytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("png.png"));
    final String mimeType = MimeTypeDeterminer.getMimeType(bytes);
    assertEquals("image/png", mimeType);
}

Conclusion

In this article we saw how to extract the MIME information for a file in Java. Please note this is not the only way, there are other ways which you can use to do the same thing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: