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?
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"));
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.
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).
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.
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>
This answer suggests using:
InputStream is = new BufferedInputStream(new FileInputStream(file)); mimeType = URLConnection.guessContentTypeFromStream(is); //...close stream
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With