文件下载中文名乱码问题

最近实现一个从服务器端下载文件的功能,发现下载下来的文件只要是中文名就乱码,觉得这应该是个编码问题,比较容易解决,结果试了好几种方法都不行,后来google了一个老外的帖子给解决了。据他测试在(IE8, FF16, Opera12, Chrome22)上都管用,代码如下:

String fileName ="árvíztűrőtükörfúrógép.xls";

String userAgent = request.getHeader("user-agent");

boolean isInternetExplorer =(userAgent.indexOf("MSIE")>-1);

try{

byte[] fileNameBytes = fileName.getBytes((isInternetExplorer)?("windows-1250"):("utf-8"));

String dispositionFileName ="";
for(byte b: fileNameBytes) dispositionFileName +=(char)(b &0xff);

String disposition ="attachment; filename=\""+ dispositionFileName +"\""; response.setHeader("Content-disposition", disposition);

}catch(UnsupportedEncodingException ence){

// ... handle exception ...

}

原贴地址:http://stackoverflow.com/questions/5325322/java-servlet-download-filename-special-characters/13359949#13359949
posted @ 2012-12-24 13:47  shtzsp  阅读(288)  评论(0)    收藏  举报