【问题标题】:How can I get the actual file extension in Java [duplicate]如何在 Java 中获得实际的文件扩展名 [重复]
【发布时间】:2015-10-09 13:09:37
【问题描述】:

我知道我可以这样做

String ext = FilenameUtils.getExtension("/path/to/file/foo.txt");

但是如果有人试图通过将扩展类型更改为 foo.doc 来上传 foo.exe 文件怎么办。有什么方法可以在不读取文件内容的情况下获得实际的扩展类型

【问题讨论】:

  • MIME 类型、幻数标头等

标签: java mime-types file-extension


【解决方案1】:
File file = new File("filename.asgdsag");
InputStream is = new BufferedInputStream(new FileInputStream(file));
String mimeType = URLConnection.guessContentTypeFromStream(is);

来自这个帖子:Get real file extension -Java code


同样使用 java7,你应该看看这个:

public static String probeContentType(Path path)
                           throws IOException

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType%28java.nio.file.Path%29

【讨论】:

  • 谢谢 Alexandre,让我试试这个。我试图在stackoverflow上找到它,但没有找到
  • 不要发布重复的代码,而是将帖子标记为重复并链接到重复的项目。
  • 好吧,凯文,我的错,这里有点新
  • 请注意,您不会投反对票 - 只是因为您是新人 :)
  • 我试过了,但在这种情况下我得到了 mimeType 为 null。我正在使用 mulipartFile。
猜你喜欢
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2012-03-24
  • 2020-10-13
  • 1970-01-01
  • 2017-10-28
相关资源
最近更新 更多