When do browsers send application / octet stream as Content-Type?

I am developing file upload using JSF. The application saves three dates about the file:

  • File name
  • B
  • Content-Type represented by the browser.

My problem is that some files are saved with content type = application/octet-stream , even if they are *.doc files oder *.pdf .

When does the browser transmit this type of content?
I would like to clear the database, so I need to know when the browser information is incorrect.

+7
content-type file-upload jsf
source share
2 answers

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.

+8
source share

It depends on the OS, browser, and how the user configured them. It is based on how the browser determines the file type of local files (for displaying them). In most OS / browser combinations, this is based on the file extension, but on some it can be defined in other ways. (for example: on Mac OS)

In any case, you should not rely on the type of content sent by the browser. A better approach would be to actually view the contents of the file. You may also be able to use the file name, but keep in mind that browsers will not necessarily tell you well (although it is probably still much more reliable than the type of content they send).

+2
source share

All Articles