views:

162

answers:

5

Hi All,

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

A: 

You can find here another post for the same problem.

thelost
ok this looks for a file-type map on a users system. Is this guaranteed to exist?
Richard
A: 

I know two solutions:

A interesting tutorial about this subject with a lot of various solutions I didn't try.

Kartoch
ok thanks for the links, I'll take a look
Richard
A: 

You can use URLConnection.guessContentTypeFromStream

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

You should look into this library. It does a lot of stuff (file extensions, magic data and content sniffing) to determine the content type:

Mime Type Detection Utility

naikus
A: 

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!

Pablo Fernandez
The client's I am supporting are browsers only. This is interesting suggestion, I will investigate.
Richard