How to get file type extension from byte[]
(Blob). I'm reading files from DB to byte[]
but i don't know how to automatically detect file extension.
Blob blob = rs.getBlob(1);
byte[] bdata = blob.getBytes(1, (int) blob.length());
if(currentImageType ==null){
ByteArrayInputStream is = new ByteArrayInputStream(image);
String mimeType = URLConnection.guessContentTypeFromStream(is);
if(mimeType == null){
AutoDetectParser parser = new AutoDetectParser();
Detector detector = parser.getDetector();
Metadata md = new Metadata();
mimeType = detector.detect(is,md).toString();
if (mimeType.contains("pdf")){
mimeType ="pdf";
}
else if(mimeType.contains("tif")||mimeType.contains("tiff")){
mimeType = "tif";
}
}
if(mimeType.contains("png")){
mimeType ="png";
}
else if( mimeType.contains("jpg")||mimeType.contains("jpeg")){
mimeType = "jpg";
}
else if (mimeType.contains("pdf")){
mimeType ="pdf";
}
else if(mimeType.contains("tif")||mimeType.contains("tiff")){
mimeType = "tif";
}
currentImageType = ImageType.fromValue(mimeType);
}
It's not perfect, but the Java Mime Magic library may be able to infer the file extension:
Magic.getMagicMatch(bdata).getExtension();
You mean you want to get the extension of the file for which the blob store the content? So if the BLOB stores the content of a jpeg-file, you want "jpg"
?
That's generally speaking not possible. You can make a fairly good guess by using some heuristic such as Apache Tikas content detection.
A better solution however, would be to store the mime type (or original file extension) in a separate column, such as a VARCHAR
.
Try with ByteArrayDataSource (http://download.oracle.com/javaee/5/api/javax/mail/util/ByteArrayDataSource.html) you will find getContentType() method there, which should help but I've never tried it personally.
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