1
votes

I am uploading a file to server using normal upload API's available. Now i want to check whether uploaded file is valid file.

I can have multiple file upload box on page. Which have different requirements and should accept different type of files.

For say :-

Input file 1 should take just exe
Input file 2 should take just html
Input file 3 should take just pptx

i can check extension and check is one solution but it may happen some one may fake the extension and upload txt file instead of exe and so

So how can i check whether correct type of file has been uploaded or not using java

Got some Solution for the same stuff but am unsure how to do it? Any help pls

3
which API are you using?Mr.J4mes
I am using commons-fileuploadVarun

3 Answers

1
votes

After checking the extension, you also need to check the signature of the file. This is usually somewhere in the first few bytes of the file. For a good list, refer to http://www.garykessler.net/library/file_sigs.html as it contains quite a lot of files and their signatures.

Even this is not foolproof, of course, but it's as close as you are going to get without delving into heuristics.

1
votes

For commons-fileupload API, you can get the content type as following:

FileItem file; 
String contentType = file.getContentType();

Based on that, you can provide some if-else to implement your logic. The FileItem may be DefaultFileItem.

0
votes

Try to load each file with an appropriate method. For example, try to parse the html file and try to load the pptx file with POI. It does not work for exe though.