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

本文介绍了一种解决导出Excel文件时文件名在不同浏览器中出现乱码的方法。通过判断浏览器类型,对文件名进行相应的编码转换,确保在IE和其他现代浏览器中都能正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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操作系统。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值