Ignore the value sent by the browser. It really depends on the client platform, browser and configuration.
If you need full control over the types of content based on the file extension, then it's better to define it yourself using ServletContext#getMimeType() .
String mimeType = servletContext.getMimeType(filename);
The default mime types are defined in the web.xml the servlet container in question. For example, in Tomcat, it is located in /conf/web.xml . You can expand / override it in webapp /WEB-INF/web.xml as follows:
<mime-mapping> <extension>xlsx</extension> <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type> </mime-mapping>
You can also determine the mime type based on the actual contents of the file (since the file extension may not be exact, it can be tricked by the client), but this is a lot of work. Consider using a third-party library to do all the work. I found JMimeMagic useful for this. You can use it as follows:
String mimeType = Magic.getMagicMatch(file, false).getMimeType();
Please note that it does not support all types of mimetypes as reliable. You can also consider a combination of both approaches. For example. if it returns null or application/octet-stream , use another. Or if both return a different, but "valid" mimetype type, prefer the one returned by JMimeMagic.
Oh, I almost forgot to add, in JSF you can get a ServletContext like this:
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
Or, if you are already using JSF 2.x, use ExternalContext#getMimeType() instead.
Balusc
source share