0

In my application we are uploading image/audio/video files. I have allowed some fixed set of allowed extensions of each types. If the extension does not match the list of provided extensions then it won't upload, but if the user renames the .exe, .pdf file to .jpg or .png the it would clear the UI validations and servlet will be called and upload will happen. But later that would cause a problem.

Is there any way to check the same at backend and then throw an Exception accordingly.

I have tried using :

import java.net.*;

public class FileUtils{
    public static String getMimeType(String fileUrl) throws java.io.IOException {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(fileUrl);
        return type;
    }

    public static void main(String args[]) throws Exception {
        System.out.println(FileUtils.getMimeType("file:/home/kavinder/file.pdf"));
        // this is a .jpg file renamed to .pdf
    }
}

This is returning according to extension only. And

import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
    public static void main(String args[]) {
        File f = new File("/home/kavinder/file.jpg");
        System.out.println("Mime Type of " + f.getName() + " is " + new MimetypesFileTypeMap().getContentType(f));
    }
}

This is always returning the mime type as: application/octet-stream

Thank you in advance

Danielson
  • 2,605
  • 2
  • 28
  • 51
kavinder
  • 609
  • 1
  • 5
  • 13
  • 1
    http://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java – cmbaxter Jun 05 '13 at 08:55
  • 1
    See: http://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java and http://stackoverflow.com/questions/4348810/java-library-to-find-the-mime-type-from-file-content – Moritz Petersen Jun 05 '13 at 08:55
  • Still my question is not to get mimetype I want to know if somebody renamed a file to some different format then how to check that. I realized now that checking mimetype is like checking extensions only. – kavinder Jun 05 '13 at 09:17

0 Answers0