How to get the real extension type of Multipart file

Vipul Jain picture Vipul Jain · Oct 19, 2015 · Viewed 77k times · Source

I have checked answer here, but here first they are saving it to some place and then reading it's stream and trying to check Mime type of that file

Get real file extension -Java code

But I want to know the file type before even saving it to the hard disk or at some place.

I know I can do it in these 2 more ways

File savedFile = new File(fileHandler.createTodayFolder(fileLocation) + "/" + name);
            Path path = Paths.get(file.get);
            Tika tika = new Tika();
            String checkType = tika.detect(path.toFile()); 

and

          Path path = Paths.get(savedFile.getPath());
          Files.probeContentType(path)

But in these both cases they are using somefile which is already at some location in hard disk. I want code something like this

  public @ResponseBody ResponseEntity<?> importResume(@RequestParam(value = "name", required = false) String name,
        @RequestParam("file") MultipartFile file) {

     if (file!=DESIRED_TYPE)
     {
       return Exception;
     }
}

Is there any way of doing this ???

Answer

Mathias G. picture Mathias G. · May 10, 2017

For me, the cleanest solution:

using FilenameUtils of org.apache.commons.io:

String extension = FilenameUtils.getExtension(file.getOriginalFilename());