Java 替代 Files.probeContentType?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19711956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:37:02  来源:igfitidea点击:

Alternative to Files.probeContentType?

java

提问by Click Upvote

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 preferred behavior as well).

在一个 web 项目中,用户上传他们的文件,但是当我在服务器上收到它们时,它们被存储为 .tmp 文件而不是它们的原始文件扩展名(这也是我的首选行为)。

However, this is causing a problem with Files.probeContentType(). While locally for me, on my Linux dev machine, Files.probeContentType()works correctly and does determine the right mime type, when I upload my project to the production server (amazon beanstalk), it doesn't seem to correctly determine the mime type.

但是,这会导致Files.probeContentType(). 虽然对我来说是本地的,但在我的 Linux 开发机器上,它Files.probeContentType()可以正常工作并确定正确的 mime 类型,但当我将我的项目上传到生产服务器(amazon beanstalk)时,它似乎无法正确确定 mime 类型。

From reading the javadocs, it seems that the implementation of Files.probeContentType()are different, and I think that on production server, it is reading the file extension and so, is unable to determine the content type.

从阅读javadocs,似乎实现Files.probeContentType()不同,我认为在生产服务器上,它正在读取文件扩展名等,无法确定内容类型。

What's a good, and quick alternative to Files.probeContentType()which will accept a Fileargument and return a string like image/pngas the resulting mime type?

有什么好的、快速的替代方法Files.probeContentType()可以接受一个File参数并返回一个像image/png结果 mime 类型一样的字符串?

采纳答案by Jk1

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

看看Apache Tika。它可以轻松确定 MIME 类型:

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

Here's a minimal required maven dependency:

这是一个最低要求的 Maven 依赖项:

 <dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.12</version>
 </dependency>

回答by summerbulb

This answersuggests using:

这个答案建议使用:

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
//...close stream

回答by Janakiram

This also works

这也有效

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

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