在java中设置内容类型以进行文件下载

cod*_*247 10 java types file mime-types

在我的应用程序中,我想提供文件下载工具.我将文件类型设置为response.setContentType.如何为几乎所有已知文件类型设置内容类型?有什么简单的方法吗?或者我需要像现在一样手动设置它,如下所示.

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 + "\"");
}
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

ska*_*man 10

看看javax.activation.MimetypesFileTypeMap(作为Java6的一部分,可以在以前版本下载).它有一个方法返回给定文件名的mime类型.

我自己从来没有尝试过使用它,而且你可能还需要提供一个mime类型列表.值得一看.

  • 在我的Mac OS X 10.5.8,Java 1.6.0_17上测试,新的MimetypesFileTypeMap().getContentType(filename)产生以下结果: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.[确认,作为评论的格式错误.我应该将此作为单独的答案发布,还是可以编辑的人将其置于此单独的答案中?] (2认同)