Decide content type while streaming files from servlet to client

Discussions

Web tier: servlets, JSP, Web frameworks: Decide content type while streaming files from servlet to client

  1. Hello,
    I have a problem when dertermine the content type when streaming files from servlet to the web client. What I am currently doing is set content type based on the file extension, for example for .txt files I choose "text/plain", etc. But this method is not that good cause I need to iterate over possible extensions to set the right content type, also sometimes the extensions does not give hint over its actual content type.

    So is there any methods or libraries to auto-detect the content type of a file based on its content, instead of extension? I observed that tomcat can serve files correctly even I suffix a text file with a ".exe" extension.

    Thanks
  2. Just use javax.servlet.ServletContext.getMimeType(String filename).
    It will return mime-type.
    Mime-types are detected based on your server settings.
    You can specify aditional mime-types in your application's web.xml