根据文件扩展名验证文件 [英] Validation of files based on their file extensions
问题描述
- docx
- xls
- xlsx
- txt
- rtf
阅读扩展名后,我想验证是否实际上是这些类型的文件。
例如,我有一个文件,并检查它有扩展名.xls。之后,我想检查它是否实际上是一个.xls文件或某人上传的其他格式的文件,在更改其扩展名后。
编辑:我想通过实际检查其内容而不是其扩展名来检查文件的MIME类型。如何做?
不使用外部库:
您可以使用MimetypesFileTypeMap获取文件mimetype:
文件f = new File(...);
System.out.println(new MimetypesFileTypeMap()。getContentType(f));
您可以得到类似的结果:
URLConnection.guessContentTypeFromName
两者根据文档,这些解决方案仅查看扩展名。
一个更好的选择: URLConnection.guessContentTypeFromStream
文件f = new File(...);
System.out.println(URLConnection.guessContentTypeFromStream(new FileInputStream(f)));
这个尝试从文件的第一个字节猜测 - 警告这只是一个猜测 - 我发现它在大多数情况下起作用,但无法检测到一些明显的类型。
我推荐两者的组合。
I get files from queues in Java. They may be of following formats.
- docx
- doc
- xls
- xlsx
- txt
- rtf
After reading their extensions, I want to validate whether they are actually files of these types.
For example, I got a file and checked that it has extension .xls. Afterwards, I want to check whether it is actually an .xls file or someone uploaded file of some other format after changing its extension.
EDIT: I'd like to check the file's MIME type by actually checking its content, not its extension. How it can be done?
Without using external libraries:
You can get the file mimetype using MimetypesFileTypeMap:
File f = new File(...);
System.out.println(new MimetypesFileTypeMap().getContentType(f));
You can get a similar result with: URLConnection.guessContentTypeFromName Both these solutions, according to the documentation, look only at the extension.
A better option: URLConnection.guessContentTypeFromStream
File f= new File(...);
System.out.println(URLConnection.guessContentTypeFromStream(new FileInputStream(f)));
This try to guess from the first bytes of the file - be warned this is only a guess - I found it works in most cases, but fails to detect some obvious types.
I recommend a combination of both.
这篇关于根据文件扩展名验证文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!