/**
* 区分ie 和其他浏览器的下载文件乱码问题
* @param request
* @param fileName
* @return
*/
public String getFileName(HttpServletRequest req,String fileName){
String userAgent = req.getHeader("user-agent");
userAgent = userAgent ==null?"":userAgent.toLowerCase();
String name = fileName;
try { //针对IE或者以IE为内核的浏览器:
if(userAgent.contains("msie") ||userAgent.contains("trident")){
name = URLEncoder.encode(name, "UTF-8");
}else{
name = new String(name.getBytes(), "iso-8859-1");
}
} catch (Exception e) {
throw new SysException(ERRORConstants.COMMON_SYSTEM_ERROR, e);
}
return name;
}
网上很多例子是用 msie 和like Gecko 来做区分,说ie11去除了msie;
亲自测试 谷歌浏览器也带like Gecko,ie11的 msie没有移除,并且带有trident标记
结论是 不用用like Gecko来做区分,最后
public void exportExcel(HttpServletRequest req,HttpServletResponse response) {
try{
response.setContentType("application/octet-stream");
String excelName = "文件名";
response.addHeader("Content-Disposition", "attachment;filename="+getFileName(req,excelName)+".xls");
OutputStream out = response.getOutputStream();
testService.export(out);
}catch(Exception e){
//
}
}
|