Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to Files.probeContentType?

Tags:

java

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).

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.

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.

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

like image 240
Ali Avatar asked Oct 31 '13 16:10

Ali


People also ask

How do I find the content type for a file?

To fetch mime type for a file, you would simply use Files and do this in your code: Files. probeContentType(Paths. get("either file name or full path goes here"));

How do I set the MIME type of a file in Java?

To Change the Default MIME TypeSelect the Configuration. Select the configuration from the configurations list. Click Configurations tab to get the available configurations. Select the Virtual Server.

How do I find MIME type?

string mimeType = MimeMapping. GetMimeMapping(fileName); If you need to add custom mappings you probably can use reflection to add mappings to the BCL MimeMapping class, it uses a custom dictionary that exposes this method, so you should invoke the following to add mappings (never tested tho, but should prob. work).

How do you validate a file type in Java?

java“. The method getExtension(String) will check whether the given filename is empty or not. If filename is empty or null, getExtension(String filename) will return the instance it was given. Otherwise, it returns extension of the filename.


2 Answers

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

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

Here's a minimal required maven dependency:

 <dependency>     <groupId>org.apache.tika</groupId>     <artifactId>tika-core</artifactId>     <version>1.12</version>  </dependency> 
like image 110
Jk1 Avatar answered Sep 28 '22 08:09

Jk1


This answer suggests using:

InputStream is = new BufferedInputStream(new FileInputStream(file)); mimeType = URLConnection.guessContentTypeFromStream(is); //...close stream 
like image 20
summerbulb Avatar answered Sep 28 '22 09:09

summerbulb