views:

644

answers:

1

Hi...

In my application i like to provide file download facility. I set the file types to response.setContentType. How can I set the content types for almost all known file types? Is there any easy way? or I need to set it manually like i do now, which is given below.

if (pictureName.indexOf("jpg") > 0) {
                            res.setContentType("image/jpg");
                        }else if (pictureName.indexOf("gif") > 0) {
                            res.setContentType("image/gif");
                        } else if (pictureName.indexOf("pdf") > 0) {
                            res.setContentType("application/pdf");
                            res.setHeader("Content-Disposition", "inline; filename=\"" + pictureName + "\"");
                        } else if (pictureName.indexOf("html") > 0) {
                            res.setContentType("text/html");
                        } else if (pictureName.indexOf("zip") > 0) {
                            res.setContentType("application/zip");
                            res.setHeader("Content-Disposition", "attachment; filename=\"" + pictureName + "\"");
                        }

thanks :)

+1  A: 

Take a look at javax.activation.MimetypesFileTypeMap (comes as part of Java6, can be downloaded for prior version). It has a method that returns the mime type for a given filename.

I've never tried using it myself, though, and it's possible you'll still need to supply it with a list of mime types. Worth a look, though.

skaffman
Tested on my Mac OS X 10.5.8, Java 1.6.0_17, new MimetypesFileTypeMap().getContentType(filename)produces these results: x.jpg image/jpeg, x.jpeg image/jpeg, x.gif image/gif, x.pdf application/octet-stream, x.html text/html, x.zip application/octet-stream.[Ack, bad formatting as a comment. Should I post this as a separate answer, or someone who can edit put it in this one?]
Kevin Reid
@Kevin: I'm not sure, are you supporting my answer, or disagreeing with it? :)
skaffman
Trying to provide data on how well this solution works. No opinion, really.
Kevin Reid
hi skaffman... for me, i think this is the ideal solution.... :)
coder247