Java中识别文件类型
请帮我找出正在上传的文件的类型。 我想区分excel类型和csv类型。
MIMEType 对于这两个文件返回相同的结果。请帮忙。
Please help me to find out the type of the file which is being uploaded.
I wanted to distinguish between excel type and csv.
MIMEType returns same for both of these file. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我使用 Apache Tika 它使用魔术字节模式和通配提示(文件扩展名)来识别文件类型来检测 MIME 类型。它还支持对文件内容的额外解析(我并没有真正使用)。
下面是一个快速而简单的示例,说明如何使用 Tika 来检测文件类型,而不需要对文件执行任何额外的解析:
I use Apache Tika which identifies the filetype using magic byte patterns and globbing hints (the file extension) to detect the MIME type. It also supports additional parsing of file contents (which I don't really use).
Here is a quick and dirty example on how Tika can be used to detect the file type without performing any additional parsing on the file:
我希望这会有所帮助。取自一个不是我的例子:
}
对于 excel 和 csv 类型来说也是如此。未测试。
I hope this will help. Taken from an example not from mine:
}
Same may be true for excel and csv types. Not tested.
我想出了一种更便宜的方法来使用
java.nio.file.Files
- 或 -
希望有帮助。
干杯。
I figured out a cheaper way of doing this with
java.nio.file.Files
- or -
Hope that helps.
Cheers.
更好的方法 不使用
javax.activation.*
:A better way without using
javax.activation.*
:如果您已经在使用 Spring,这适用于 csv 和 excel:
或者使用 javax.activation 您可以更新 mime.types 文件。
If you are already using Spring this works for csv and excel:
or with javax.activation you can update the mime.types file.
CSV 将以文本开头,Excel 类型很可能是二进制。
然而,最简单的方法是尝试使用 POI 加载 Excel 文档。如果失败,请尝试将文件加载为 CSV,如果失败,则可能不是两种类型。
The CSV will start with text and the excel type is most likely binary.
However the simplest approach is to try to load the excel document using POI. If this fails try to load the file as a CSV, if that fails its possibly neither type.