Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting content type in Java for file download

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 + "\"");
}
like image 730
coder247 Avatar asked Feb 11 '10 14:02

coder247


2 Answers

URLConnection.getFileNameMap().getContentTypeFor(string) works for txt, pdf, avi; fails for doc, odt, mp3...

like image 166
Ray Hulha Avatar answered Sep 21 '22 23:09

Ray Hulha


To giving a working example of what @skaffman listed when using a Servlet:

String fileName = "c:/temp/URL.txt";
MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
response.setContentType(mimetypesFileTypeMap.getContentType(fileName));
response.getOutputStream().write(Files.readAllBytes(Paths.get(fileName)));
like image 22
Doug Avatar answered Sep 21 '22 23:09

Doug