httpServletResponse.setContentType("application/vnd.ms-excel");
Util.setFileDownloadHeader(httpServletRequest,httpServletResponse,"用户列表.xls");
setFileDownloadHeader函数主要是根据当前用户的浏览器不同,对文件的名字进行不同的编码设置,从而解决不同浏览器下文件名中文乱码问题
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
final String userAgent = request.getHeader("USER-AGENT");
try {
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
finalFileName = URLEncoder.encode(fileName,"UTF8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
finalFileName = new String(fileName.getBytes(), "ISO8859-1");
}else{
finalFileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
} catch (UnsupportedEncodingException e) {
}
}
分享到:
2015-02-12 09:56
浏览 1641
评论