Simple question: how can I get MIME type (or content type) of an InputStream
, without saving file, for a file that a user is uploading to my servlet?
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 media type (also known as a Multipurpose Internet Mail Extensions or MIME type) indicates the nature and format of a document, file, or assortment of bytes. MIME types are defined and standardized in IETF's RFC 6838.
I wrote my own content-type detector for a byte[] because the libraries above weren't suitable or I didn't have access to them. Hopefully this helps someone out.
// retrieve file as byte[] byte[] b = odHit.retrieve( "" ); // copy top 32 bytes and pass to the guessMimeType(byte[]) funciton byte[] topOfStream = new byte[32]; System.arraycopy(b, 0, topOfStream, 0, topOfStream.length); String mimeGuess = guessMimeType(topOfStream);
...
private static String guessMimeType(byte[] topOfStream) { String mimeType = null; Properties magicmimes = new Properties(); FileInputStream in = null; // Read in the magicmimes.properties file (e.g. of file listed below) try { in = new FileInputStream( "magicmimes.properties" ); magicmimes.load(in); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // loop over each file signature, if a match is found, return mime type for ( Enumeration keys = magicmimes.keys(); keys.hasMoreElements(); ) { String key = (String) keys.nextElement(); byte[] sample = new byte[key.length()]; System.arraycopy(topOfStream, 0, sample, 0, sample.length); if( key.equals( new String(sample) )){ mimeType = magicmimes.getProperty(key); System.out.println("Mime Found! "+ mimeType); break; } else { System.out.println("trying "+key+" == "+new String(sample)); } } return mimeType; }
magicmimes.properties file example (not sure these signatures are correct, but they worked for my uses)
# SignatureKey content/type \u0000\u201E\u00f1\u00d9 text/plain \u0025\u0050\u0044\u0046 application/pdf %PDF application/pdf \u0042\u004d image/bmp GIF8 image/gif \u0047\u0049\u0046\u0038 image/gif \u0049\u0049\u004D\u004D image/tiff \u0089\u0050\u004e\u0047 image/png \u00ff\u00d8\u00ff\u00e0 image/jpg
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