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

How to get file type extension from byte[] (Blob). I read files from DB to byte[] , but I do not know how to automatically determine the file extension.

 Blob blob = rs.getBlob(1); byte[] bdata = blob.getBytes(1, (int) blob.length()); 
+7
source share
6 answers

Do you want you to get the file extension for which blob stores content? So, if a blob stores the contents of a jpeg file, do you want "jpg" ?

This is generally impossible. You can make a pretty good guess using some heuristics, such as detecting Apache Tikas content .

However, the best solution would be to save the mime type (or the original file extension) in a separate column, such as VARCHAR .

+9
source

Try it with ByteArrayDataSource (http://download.oracle.com/javaee/5/api/javax/mail/util/ByteArrayDataSource.html), you will find the getContentType () method that should help, but I never tried it personally.

+2
source

This is not ideal, but the Java Mime Magic library can output the file extension:

 Magic.getMagicMatch(bdata).getExtension(); 
+2
source

An alternative to using a separate column is Magic Numbers . Here are a few pseudo codes:

 getFileExtn(BLOB) { PNGMagNum[] = {0x89, 0x50, 0x4E, 0x47} if(BLOB[0:3] == PNGMagNum) return ".png" //More checks... } 

You will need to do this for each type of file that you support. Some obscure file types that you may need to figure out through a hex editor (a magic number is always the first few bytes of code). The advantage of using a magic number is that you get the actual file type, and not what the user simply decided to name.

+1
source
 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); } 
+1
source

There is a decent method in the JDK URLConnection class, see the following answer: Getting the Mime type in Java

0
source

Source: https://habr.com/ru/post/895408/


All Articles