Skip to content

MIME type detection from binary data

MIME type detection from binary data is the process of inspecting the raw byte stream of a file (specifically an image) to determine its internet media type, rather than relying solely on file extensions.^[600-developer-frontend-jquery-jquery-validation-file-upload.md]

Implementation using URLConnection

In a Java environment, this can be achieved by wrapping the byte data in a BufferedInputStream and utilizing the guessContentTypeFromStream method from java.net.URLConnection.^[600-developer-frontend-jquery-jquery-validation-file-upload.md]

This approach returns a string representing the MIME type, which can then be compared against expected values to validate the file format before processing or storage.^[600-developer-frontend-jquery-jquery-validation-file-upload.md]

Validation Logic

The detection method allows for specific validation checks. For example, an implementation might verify that the detected MIME type contains strings such as "png", "jpg", or "jpeg".^[600-developer-frontend-jquery-jquery-validation-file-upload.md] If the detected type does not match the expected criteria, the system can raise a runtime exception to reject the file.^[600-developer-frontend-jquery-jquery-validation-file-upload.md]

Data URI Format

Once validated, the binary data is commonly converted into a [[Base64]] string for embedding directly into HTML or other text-based formats. The standard structure for this Data URI is:^[600-developer-frontend-jquery-jquery-validation-file-upload.md]

data:[<mime type>][;base64],<data>

For example, a PNG image is represented as data:image/png;base64,iVBORw0KGgo....^[600-developer-frontend-jquery-jquery-validation-file-upload.md]

  • [[Base64]]
  • [[Client-side file upload]]

Sources

^[600-developer-frontend-jquery-jquery-validation-file-upload.md]