codenow
codenow

Reputation: 31

multipart file upload check mime type in java

I am using mimeutil for checking the mimetype of a file. And only allowing csv and json files. But getting this mimetype for a json file "application/x-ipynb+json" mime type which is nowhere found. Any help will be appreciated to get the exact mime type of a file if also renamed a exe file to json which should not be allowed for security reasons. Refer below code for reference:

public static String verifyExtension(MultipartFile File){
String mimeType = null;
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.ExtensionMimeDetector");
        //MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.OpendesktopMimeDetector");
        MimeUtil.registerMimeDetector(System.getProperty("os.name").startsWith(
              "Windows") ? "eu.medsea.mimeutil.detector.WindowsRegistryMimeDetector"
              : "eu.medsea.mimeutil.detector.OpendesktopMimeDetector");

        Collection<?> mimeTypes = null;
        try {
            mimeTypes = MimeUtil.getMimeTypes(File.getBytes());
            if(mimeTypes.equals("application/vnd.ms-excel") || mimeTypes.equals("application/json") 
                    || mimeTypes.equals("application/octet-stream"))
            {
                System.out.println("File typ is csv or json");
                mimeType = "success";
            }else{
                mimeType = "fail";
            }
        } catch (MimeException e1) {
            System.out.println(e1.getMessage());
            mimeType = "fail";
        } catch (IOException e1) {
            System.out.println(e1.getMessage());
            mimeType = "fail";
        }
}

Upvotes: 1

Views: 9169

Answers (1)

Michal
Michal

Reputation: 2273

Your issue is that MIME type checks in java are based on file extension.

In order to run actual file analysis try Apache Tika Mime Magic Detection.

Also, you can try one of the following:

  1. ZIP the file before upload, then unzip on the server and test mime type
  2. Upload through scalable 3rd party solution e.g. S3 bucket
  3. Rename the uploaded file but send the file name in a header or URL parameter and test that for mime type

Upvotes: 1

Related Questions