Tech Enthusiast
Tech Enthusiast

Reputation: 287

How to validate a file with valid extension?

Lets say the input to my Java code is a jpeg file. How can i verify it before starting process that the input is having a valid extension. Sometimes the user upload a pdf file with extension modified to a jpeg, thus crashing the code.

There is a point of magic number with each file. But is there any alternative to solve this problem.

Upvotes: 1

Views: 30516

Answers (6)

stesting-errorfree
stesting-errorfree

Reputation: 1

I had a case where i need to verify image file is .JPEG inside the zip file with out unzip the file.

This method works:

public void ZipFileExtractAndVerifyImageFileExtension(String FileNamewithPath) {
    File file = new File(FileNamewithPath);
    InputStream input;
    try {

      input = new FileInputStream(file);
      ZipInputStream zip = new ZipInputStream(input);
      ZipEntry entry;

      while(zip.getNextEntry()!=null) {
          entry = zip.getNextEntry();
          if(entry!= null) {
             if(entry.getName().endsWith(".JPG") || entry.getName().endsWith(".JPEG")||entry.getName().endsWith(".jpeg")) {
                System.out.println("Current File Name=" + entry.getName() + " Current File Size is " + entry.getSize());
             }     
          }
       }
       zip.close();
       input.close();
     
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

Upvotes: 0

Paul Hicks
Paul Hicks

Reputation: 13999

The magic number solution is already implemented: see this topic for links to the Java Mime Magic Library.

Upvotes: 3

Durandal
Durandal

Reputation: 20059

You can not be sure of a files type, unless you completely parse the file and verify that it adheres completely to the format specification. Only then you can be sure.

Checking the magic number is a quick way of checking with a high probability to guess the type correctly. But obviously its not foolproof, its easy to make a file that starts with the bytes FF D8 FF, which would look like its a jpeg, but there is obviously no guarantee that its really a jpeg.

Or just rely on the file extension.

You just have to make a trade between reliability and simplicity. If you want simple, trust the file extension. If you want safety, verify the file contents.

Upvotes: 1

Alberto
Alberto

Reputation: 1579

If you want just to check the file name, you can do this:

public boolean checkJPEG(File file) {
   String fileName = file.getName().toUpperCase();
   return fileName.endsWith(".JPG") || fileName.endsWith(".JPEG");
}

But this method check only the file name, not the content. A more complete method include the magic number test.

public boolean checkJPEG(File file) throws IOException {
   String fileName = file.getName().toUpperCase();
   boolean extension = fileName.endsWith(".JPG") || fileName.endsWith(".JPEG");
   if (!extension) {
      return false;
   }
   FileInputStream in = null;
   try {
      in = new FileInputStream(file)
      byte[] magic = new byte[3];
      int count = in.read(magic);
      if (count < 3) return false;
      return magic[0] == 0xFF && magic[1] == 0xD8 && magic[2] == 0xFF;
   } finally {
      try {
         if (in != null) in.close();
      } catch (IOException ex) {}
   }
}

List of file signatures here: http://en.wikipedia.org/wiki/List_of_file_signatures

Upvotes: 4

Vinayak Pingale
Vinayak Pingale

Reputation: 1315

a. This function below will list all the extension in the directory. What you can do is list all and get the extension of all files and can check which files can be uploaded. You can provide a client side validation on the UI that only .jpeg files are allowed.

public static void main(String args[]) {
        System.out.println("GET");
        File fileObj = new File("D:\\");
        File[] listAll = fileObj.listFiles();
        for (File file : listOfFiles) {
        if (file.isFile()) {
            System.out.println("Extension ."+file.getName().substring(file.getName().lastIndexOf('.')+1));
        }
        }
    }

b. Regarding miscrepancies of the extension i have not gone through such situation. May be the point specified by eltabo can help.

Upvotes: 0

eltabo
eltabo

Reputation: 3807

Check the file signature:

http://www.filesignatures.net/index.php?search=JPEG&mode=EXT

http://en.wikipedia.org/wiki/List_of_file_signatures

You can verify file type by reading few bytes.

Regards.

Upvotes: 0

Related Questions