Alternative to Files.probeContentType?

前端 未结 3 939
温柔的废话
温柔的废话 2021-01-01 09:35

In a web project, users upload their files, but when I receive them on the server, they are being stored as .tmp files rather than their original file extension (this is my

相关标签:
3条回答
  • 2021-01-01 10:03

    Take a look at the Apache Tika. It can easily determine a mime type:

     Tika tika = new Tika();
     File file = ...
     String mimeType = tika.detect(file);
    

    Here's a minimal required maven dependency:

     <dependency>
        <groupId>org.apache.tika</groupId>
        <artifactId>tika-core</artifactId>
        <version>1.12</version>
     </dependency>
    
    0 讨论(0)
  • 2021-01-01 10:08

    This answer suggests using:

    InputStream is = new BufferedInputStream(new FileInputStream(file));
    mimeType = URLConnection.guessContentTypeFromStream(is);
    //...close stream
    
    0 讨论(0)
  • 2021-01-01 10:18

    This also works

    String mimeType = URLConnection.guessContentTypeFromName(new File(path).getName());

    0 讨论(0)
提交回复
热议问题