HttpServletRequest: How to determine Content-Type of requested asset

末鹿安然 提交于 2019-12-12 17:57:35

问题


I am writing a quick-and-dirty static file server using Jetty. I need to set the Content-Type for each response:

HttpServletResponse.setContentType("content/type");

For a given file request, how do I reliably determine what content type to set? Is it a question of examining the file extension, or is there a more sophisticated method? (E.g what if there is no file extension, or the extension does not reflect the content type?)

Thanks Richard


回答1:


Can't you just check the request header Content-Type and set the response to that?

I don't know the kind of clients you are planning to support but if they are browsers I guess you should be fine with that. If you control the clients, it's a good practice that they send you that header anyways.

Good Luck!




回答2:


You can use URLConnection.guessContentTypeFromStream

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);



回答3:


Since you're using the HttpServletResponse object in your question, I'm assuming you have the ServletContext available to you in your Controllers. I just solved this same problem just using methods available from the servletContext.

Since you're writing a file server, you can just pass in the path to the file in the getMimeType method of the ServletContext, and it should return the mimeType, if it can determine it.

String path = "/js/example.js";
String mimeType = getServletContext().getMimeType(path);
resp.setContentType(mimeType);   // HttpServletResponse object

NOTE: Sets the content type to "application-x/javascript" in this particular example.

Additional information: I believe this solution also assumes your files are stored in a location accessible to the ServletContext. If not, then one of the other solutions may be best.



来源:https://stackoverflow.com/questions/3433844/httpservletrequest-how-to-determine-content-type-of-requested-asset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!