1、什么是mime-type
简单来讲,它的作用就是服务器告诉浏览器你这个内容到底是个什么东东,是一张网页?还是一张图片?还是一个视频?浏览器只有知道了你这是个什么东西,才能正确处理它,mime就是这个东西,服务器通过Content-Type这个header来指定mime。
2、Java获取Content-Type(Mime-Type)的方法
(1)jdk1.7自带方法
public static String getContentType(String filePath) {
String contentType = null;
try {
contentType = java.nio.file.Files.probeContentType(java.nio.file.Paths.get(filePath));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(contentType);
return contentType;
}(2)javax.activation.MimetypesFileTypeMap
public static String getContentType(String filePath) {
String contentType = null;
try {
contentType = new javax.activation.MimetypesFileTypeMap().getContentType(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(contentType);
return contentType;
}(3)java.net.URLConnection
public static String getContentType(String filePath) {
java.net.FileNameMap fileNameMap = java.net.URLConnection.getFileNameMap();
String contentType = fileNameMap.getContentTypeFor(filePath);
System.out.println(contentType);
return contentType;
}(4)其它方法
以上3种方法效果都不好,只能正确获取部分文件的Content-Type(Mime-Type)。最好的办法是找到所有的Content-Type,放到Map或Enum中,方便且全面。文章源自新逸网络-https://www.xinac.net/9069.html
可查找的地方有:文章源自新逸网络-https://www.xinac.net/9069.html
- tomcat的
web.xml文件
- nginx的
mime.types文件 - https://www.w3school.com.cn/media/media_mimeref.asp
- http://www.iana.org/assignments/media-types/media-types.xhtml
- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
- https://www.runoob.com/http/http-content-type.html
- https://tool.oschina.net/commons/
- http://tools.jb51.net/table/http_content_type/
文章源自新逸网络-https://www.xinac.net/9069.html 文章源自新逸网络-https://www.xinac.net/9069.html

新逸IT技术
扫一扫关注微信公众号









评论