实例:
String poorName= dataMap.get("NAME").toString();
String villageName = dataMap.get("ADDRESS").toString();
String filename=villageName+"-"+poorName+".doc";
response.setContentType("application/doc");
final String userAgent = request.getHeader("USER-AGENT");
if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
filename = URLEncoder.encode(filename,"UTF-8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
filename = new String(filename.getBytes(), "ISO8859-1");
}else{
filename = URLEncoder.encode(filename,"UTF-8");//其他浏览器
}
response.addHeader("Content-Disposition", "attachment;filename="
+filename);/这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
Writer out = response.getWriter();
也可以直接把方法提取出来供以后直接使用:
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) {
}
}