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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2244892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:11:19  来源:igfitidea点击:

setting content type in java for file download

javafiletypesmime-types

提问by coder247

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.

在我的应用程序中,我喜欢提供文件下载工具。我将文件类型设置为 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 + "\"");
}

Thanks :)

谢谢 :)

采纳答案by skaffman

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.

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

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.

不过,我自己从未尝试过使用它,而且您可能仍需要为它提供一个 mime 类型列表。不过值得一看。

回答by Ray Hulha

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

URLConnection.getFileNameMap().getContentTypeFor(string)适用于 txt、pdf、avi;doc、odt、mp3 失败...

回答by Doug

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

给出一个使用 Servlet 时 @skaffman 列出的工作示例:

        String fileName = "c:/temp/URL.txt";
        MimetypesFileTypeMap mimetypesFileTypeMap=new MimetypesFileTypeMap();
        response.setContentType(mimetypesFileTypeMap.getContentType(fileName));
        response.getOutputStream().write(Files.readAllBytes(Paths.get(fileName)));