Java / ImageIO Check format before reading entire file?

I am developing a web application that will allow users to upload images. I am worried about file size, especially if they are not valid formats.

I am wondering if there is a way in java (or a third-party library) to check the allowed file formats (jpg, gif and png) before reading the entire file.

+4
source share
3 answers

If you want to support only a few types of images, you can start by loading (up) the image, and at some point use the first few bytes to check if you want to continue downloading.

Quite a few image formats can be recognized using the first few bytes, a magic number . If the number matches, you don't know if the file is really valid, but it can be used to match the extension and magic number to prevent it from really matching at all.

Check out this page to check out some Java that test mime types. Read the docs or source to see if any given method requires the entire file, or can handle multiple bytes. I have not used these libraries :)

Also check out this page , which also lists some java libraries and some documents on which the discovery is based.

Be sure to add some feedback if you manage to find something you like!

+3
source

You do not need third-party libraries. The code you have to write is simple.

At the moment when you are processing your downloads, filter files by their extension. This is not ideal, but will take into account most cases.

However, this means that the files are already uploaded to the server. You can use the client side javascript bit to perform the same operation - check if the file upload component value contains a valid file type - .jpg , .png , etc.

0
source
 function extensionsOkay(fval) { var extension = new Array(); extension[0] = ".png"; extension[1] = ".gif"; extension[2] = ".jpg"; extension[3] = ".jpeg"; extension[4] = ".bmp"; // No other customization needed. var thisext = fval.substr(fval.lastIndexOf('.')).toLowerCase(); for(var i = 0; i < extension.length; i++) { if(thisext == extension[i]) { $('#support-documents').hide(); return true; } } // show client side error message $('#span.failed').show(); return false; } 
0
source

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


All Articles