Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file type extension from byte[] (Blob)

Tags:

java

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());
like image 307
senzacionale Avatar asked Aug 19 '11 10:08

senzacionale


4 Answers

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);
            }
like image 181
Akin Okegbile Avatar answered Nov 15 '22 18:11

Akin Okegbile


It's not perfect, but the Java Mime Magic library may be able to infer the file extension:

Magic.getMagicMatch(bdata).getExtension();
like image 32
Adam Paynter Avatar answered Nov 15 '22 20:11

Adam Paynter


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.

like image 28
aioobe Avatar answered Nov 15 '22 19:11

aioobe


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.

like image 42
Kris Avatar answered Nov 15 '22 20:11

Kris