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 + "\"");
}
URLConnection.getFileNameMap().getContentTypeFor(string)
works for txt, pdf, avi; fails for doc, odt, mp3...
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With