简要概述:
本人用springboot开发网站,手动处理js和css文件请求,报错:CSS 因 Mime 类型不匹配而被忽略
后台代码:
如下三个代码块
@GetMapping("/Guest/ASN1/{FileName}")
public void GetFiles(@PathVariable("FileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
if (fileName == null) {
return;
}
ResponseFile.ResponseWriteStreamFile(UserDir.GetResourceDir() + "asn1js/" + fileName, response);
}
public static void ResponseWriteStreamFile(String fileName, HttpServletResponse response) {
OutputStream httpResponseStream = null;
File fileTmp = null;
fileTmp = new File(fileName);
try {
if (fileTmp.length() < 0) {
fileTmp = null;
return;
}
response.setContentLengthLong(fileTmp.length());
System.out.println(fileName + " " + fileTmp.length());
httpResponseStream = response.getOutputStream();
ResponseWriteStreamFile(fileName, httpResponseStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileTmp = null;
}
public static void ResponseWriteStreamFile(String fileName, OutputStream httpResponseStream) {
FileInputStream in = null;
int i = 0;
byte[] buf = null;
try {
in = new FileInputStream(fileName);
buf = new byte[2048];
while (true) {
i = in.read(buf);
if (i <= 0) {
break;
}
httpResponseStream.write(buf, 0, i);
}
in.close();
in = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in = null;
}
}
前端代码:
关键引用css和js部分,就是一般引用,没什么特殊处理,如下:
<link rel="stylesheet" type="text/css" href="/Guest/ASN1/index.css" />
<script type="text/javascript" src="/Guest/ASN1/hex.js"></script>
<script type="text/javascript" src="/Guest/ASN1/base64.js"></script>
<script type="text/javascript" src="/Guest/ASN1/oids.js"></script>
<script type="text/javascript" src="/Guest/ASN1/int10.js"></script>
<script type="text/javascript" src="/Guest/ASN1/asn1.js"></script>
<script type="text/javascript" src="/Guest/ASN1/dom.js"></script>
<script type="text/javascript" src="/Guest/ASN1/index.js"></script>
运行报错:
如下在IE11里面报错,报错之后,css文件不起作用。但是在谷歌浏览器不会报错,出错如下:
有时候还会报另外错:css 未载入,因为它的 MIME 类型 “text/plain“ 不是 “text/css“
分析问题:
费劲查了很久终于明白,根据提示,
是因为http头,ContentType不是浏览器所期望的。
因为手动控制下载css和js,ContentType就没有设置(如果自动下载springboot会设置好ContentType),所以就不确定是什么值,有可能是text/plain。
解决问题:
根据下载css还是js,分别设置好ContentType,上面第一个代码函数GetFiles,改为如下:
@GetMapping("/Guest/ASN1/{FileName}")
public void GetFiles(@PathVariable("FileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
if (fileName == null) {
return;
}
if (fileName.endsWith(".css")) {
response.setContentType("text/css");
} else if (fileName.endsWith(".js")) {
response.setContentType("text/javascript");
}
ResponseFile.ResponseWriteStreamFile(UserDir.GetResourceDir() + "asn1js/" + fileName, response);
}
注意添加了代码段:
if (fileName.endsWith(“.css”)) {
response.setContentType(“text/css”);
} else if (fileName.endsWith(“.js”)) {
response.setContentType(“text/javascript”);
}