您的位置:首页 > 编程语言 > Java开发

javaweb文件下载中文名乱码问题

2015-10-14 15:53 471 查看
IE:通过URLEncoder对filename进行UTF8编码

其他浏览器(firefox、chrome、safari、opera),通过字节转换成ISO-8859-1

if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
filename = URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
}


public class DataExportAction extends Action{

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){

DataForm formBean = (DataForm)form;
DataService dataService = (DataService)getBean("DataService");

...// 此处省略对 formBean 进行处理

response.reset();

fileName = "中文乱码问题";

ServletOutputStream out = response.getOutputStream();

String agent = request.getHeader("User-Agent");
if(agent != null && agent.toUpperCase().indexOf("MSIE") != -1){
response.setHeader("Content-Disposition","attachment;
fileName=" +URLEncoder.encode(fileName,"utf-8") + ".xls")
}else{
response.setHeader("Content-Disposition","attachment;
fileName=" + new String(fileName.getBytes("utf-8"),"iso-8859-1") + ".xls");
}

//定义输出类型
response.setContentType("APPLICATION/msexcel");

//...
DataService.exportDataToExcel(formBean,out);

out.close();
response.flushBuffer();
}


通过分析userAgent属性来判断浏览器的类型及版本:

Windows操作系统浏览器系列:

IE浏览器系列:

特征表现:均以 “mozilla/” 开头,”msie x.0;” 中的x表示其版本;

判断方法:粗略判断可以只检索 “msie x.0;” 字符串即可,严格判断可检索 “mozilla/x.0 (compatibal; msie x.0; windows nt”,不过一般没有这个必要

Windows版Firefox:

特征表现:以”mozilla/x.0”开头,包含”windows nt”,”gecko/”和”firefox/” ;

判断方法:粗略判断可以只检索 “firefox/”和”windows nt” 字符串,严格判断可以检索”mozilla/” ,”windows nt”,”gecko/”和”firefox/” 四个字符串;

Windows版Chrome:

特征表现: 以”mozilla/x.0”开头,包含”windows nt”,”chrome/”,同时包含”applewebkit/”,”safari/”;

判断方法:粗略判断可以只检索 “windows nt”和”chrome/”字符串,严格判断可以同时检索 “mozilla/” ,”windows nt”,”applewebkit/”,”safari/”,”chrome/” 五个字符串;

Windows版Opera:

特征表现:以”opera/”开头,含有”windows nt”,”presto/” 字符串;

判断方法:粗略判断只检索 “windows nt”和”opera/”字符串,严格判断同时检索 “opera/”,”windows nt” 和 “presto/”;

Windows版Safari:

特征表现:以”mozilla/”开头,同时含有”windows nt”,”applewebkit/”,”safari/”;

判断方法:粗略判断可以检索含有 “windows nt”,”safari/” 同时不包含 “chrome/”,严格判断需要同时含有”mozilla/”,”windows nt”,”applewebkit/”,”safari/”但是不包含”chrome/”;

小结:Windows操作系统上的浏览器userAgent均包含”windows nt”字符串来表征windows操作系统。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  乱码