Edge浏览器的user-agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063
Chrome浏览器的user-agent:
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36
IE浏览器的user-agent:
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)
所以在进行文件下载时对user-agent的判断(MSIE/Trident,Edge),不同浏览器使用不同编码:
通用写法如下:
if (isMSIE) {
//IE浏览器的乱码问题解决
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
//万能乱码问题解决
fileName = new String(fileName.getBytes("GBK/GB2312"), "ISO-8859-1");
}
private String toUtf8Str(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
logger.error("error",ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) {
k += 256;
}
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
注: 使用POI下载EXCEL时,需要使用 window.location.href = xxx?a=b,否则不能弹窗下载