开发者

HttpServletRequest: How to determine Content-Type of requested asset

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 reque开发者_开发知识库st, 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


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.


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!


You can use URLConnection.guessContentTypeFromStream

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜