Richard H
Richard H

Reputation: 39055

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 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

Upvotes: 2

Views: 13750

Answers (3)

jamesmortensen
jamesmortensen

Reputation: 34038

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.

Upvotes: 2

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

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!

Upvotes: 1

YoK
YoK

Reputation: 14505

You can use URLConnection.guessContentTypeFromStream

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

Upvotes: 0

Related Questions