Skip to content

MIME type detection from byte arrays

MIME type detection from byte arrays is the process of identifying the specific media type (such as an image format) of a file by inspecting the raw binary content (byte[]) rather than relying solely on the file extension.

Implementation via Java

In a Java environment, specifically when handling file uploads (e.g., via apache commons-fileupload or ServletFileUpload), the java.net.URLConnection class can be utilized to perform this detection.^[600-developer__frontend__jquery__jquery-validation-file-upload.md]

The recommended approach involves wrapping the byte array in an input stream and passing it to the guessContentTypeFromStream method^[600-developer__frontend__jquery__jquery-validation-file-upload.md]:

private String getMimeType(byte data[]) throws Exception {
  InputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
  String mimeType = URLConnection.guessContentTypeFromStream(is);
  return mimeType;
}

Common Formats

When implementing validation logic for images, the detection typically distinguishes between standard formats. For example, a common check ensures the content is identified as one of the following^[600-developer__frontend__jquery__jquery-validation-file-upload.md]:

  • PNG
  • JPG
  • JPEG

Validation Logic

A robust implementation often includes validation steps. For instance, the getMimeType result can be checked using StringUtils.containsIgnoreCase to verify the format^[600-developer__frontend__jquery__jquery-validation-file-upload.md]. If the detected MIME type does not match the expected allowlist, the system may raise a RuntimeException^[600-developer__frontend__jquery__jquery-validation-file-upload.md].

Usage Context

This technique is frequently applied during the processing of multipart/form-data requests, where files are converted into byte arrays for storage or further manipulation, such as converting images to [[Base64]] strings^[600-developer__frontend__jquery__jquery-validation-file-upload.md].

Sources

^[600-developer__frontend__jquery__jquery-validation-file-upload.md]