Java 文件扩展名字母大小写对MIME类型重要吗?

Java 文件扩展名字母大小写对MIME类型重要吗?,java,servlets,Java,Servlets,今天我无意中发现了这一点: String fileName = "test.JPG"; servletContext.getMimeType(fileName); // null 明显的修正: servletContext.getMimeType(fileName.toLowerCase()); // image/jpeg 在检测MIME类型时,我不担心文件扩展名字母的情况,对吗 您已经在问题中提供了示例,让我解释一下为什么会发生这种情况 如果您使用的是Tomcat,在检测mim

今天我无意中发现了这一点:

String fileName = "test.JPG";
servletContext.getMimeType(fileName);  // null
明显的修正:

servletContext.getMimeType(fileName.toLowerCase());  // image/jpeg    

在检测MIME类型时,我不担心文件扩展名字母的情况,对吗

您已经在问题中提供了示例,让我解释一下为什么会发生这种情况

如果您使用的是Tomcat在检测mimeType时,您需要为这种情况而烦恼

为什么?

Tomcat将mimetype存储在名为mimeMappings的HashMap中

HashMap的键区分大小写。

public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("abc", "abc");
  map.put("xyz", "xyz");
  map.put("ABC", "ABC");

  System.out.println(map);
}
Output
{ABC=ABC, abc=abc, xyz=xyz}
下面的代码块取自
org.apache.catalina.core.StandardContext

 private HashMap<String, String> mimeMappings =
434         new HashMap<String, String>();
私有HashMap mimeMappings=
434新的HashMap();
您知道java.util.HashMap中的键区分大小写。这意味着您可以将“abc”和“abc”作为键保留在同一地图中

参见此示例。

public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("abc", "abc");
  map.put("xyz", "xyz");
  map.put("ABC", "ABC");

  System.out.println(map);
}
Output
{ABC=ABC, abc=abc, xyz=xyz}
publicstaticvoidmain(字符串[]args){
Map Map=newhashmap();
地图放置(“abc”、“abc”);
地图放置(“xyz”、“xyz”);
地图放置(“ABC”、“ABC”);
系统输出打印项次(map);
}
输出
{ABC=ABC,ABC=ABC,xyz=xyz}

信息:这就是为什么在Apache Commons

中的敏感映射中使用大小写,所以这不重要,但因为它是Tomcat实现的。我将坚持使用我的
.toLowerCase()
修复程序。