I was just wondering how most people fetch a mime type from a file in Java? So far I\'ve tried two utils: JMimeMagic
& Mime-Util
.
Th
The JAF API is part of JDK 6. Look at javax.activation
package.
Most interesting classes are javax.activation.MimeType
- an actual MIME type holder - and javax.activation.MimetypesFileTypeMap
- class whose instance can resolve MIME type as String for a file:
String fileName = "/path/to/file";
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
// only by file name
String mimeType = mimeTypesMap.getContentType(fileName);
// or by actual File instance
File file = new File(fileName);
mimeType = mimeTypesMap.getContentType(file);
public String getFileContentType(String fileName) {
String fileType = "Undetermined";
final File file = new File(fileName);
try
{
fileType = Files.probeContentType(file.toPath());
}
catch (IOException ioException)
{
System.out.println(
"ERROR: Unable to determine file type for " + fileName
+ " due to exception " + ioException);
}
return fileType;
}
It is better to use two layer validation for files upload.
First you can check for the mimeType and validate it.
Second you should look to convert the first 4 bytes of your file to hexadecimal and then compare it with the magic numbers. Then it will be a really secure way to check for file validations.
I was just wondering how most people fetch a mime type from a file in Java?
I've published my SimpleMagic Java package which allows content-type (mime-type) determination from files and byte arrays. It is designed to read and run the Unix file(1) command magic files that are a part of most ~Unix OS configurations.
I tried Apache Tika but it is huge with tons of dependencies, URLConnection
doesn't use the bytes of the files, and MimetypesFileTypeMap
also just looks at files names.
With SimpleMagic you can do something like:
// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);
// null if no match
if (info != null) {
String mimeType = info.getMimeType();
}
in spring MultipartFile file;
org.springframework.web.multipart.MultipartFile
file.getContentType();