-2

In the code below, how will I find the mime type of the file that just got saved in File object?

File fileBase = new File("classpath:test");
try {
    FileUtils.copyURLToFile(
            new URL(docUploadDto.getAssetFileUrl()), 
            fileBase);
} catch (MalformedURLException e) {
    responseDto.setMessage("Malformed URL : "+e.getMessage());
    responseDto.setStatus("500");
    return responseDto;
} catch (IOException e) {
    responseDto.setMessage("IO Error : "+e.getMessage());
    responseDto.setStatus("500");
    return responseDto;
}

My docUploadDto.getAssetFileUrl() can download any kind of File.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kiran S
  • 78
  • 1
  • 10
  • Files.probeContentType(path) || URLConnection.guessContentTypeFromName(file.getName()); – aran Feb 18 '19 at 09:31

1 Answers1

1

Short answer: You can't.

Long answer:

You can guess what mime type the file is supposed to be by looking at the extension and file contents. Mime types are just standardized identifiers that associate different types of file endings, such as jpg and jpeg together. They aren't found in the file itself.

Files.probeContentType(path) does indeed try its best to guess the mime as Asier said in the comment above, but the implementation is OS-specific and not complete. It's recommended to use Apache Tika instead:

Tika tika = new Tika();
MediaType type = tika.detect(new FileInputStream(fileBase));
Kilves
  • 1,028
  • 10
  • 13