zl程序教程

您现在的位置是:首页 >  Java

当前栏目

java文件下载文件名乱码问题解决方案

2023-03-14 10:24:38 时间

		        try {  
		            long fileLength = new File(downLoadPath).length();
		            String userAgent = request.getHeader("User-Agent"); 
			        
		           if (null != userAgent && -1 != userAgent.indexOf("MSIE") || null != userAgent && -1 != userAgent.indexOf("Trident")) {     // ie  
		                 fileName = java.net.URLEncoder.encode(fileName, "UTF8");  
		           } else if (null != userAgent && -1 != userAgent.indexOf("Mozilla")) {           // 火狐,chrome等  
		        	   fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
		           }  
			           
			        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
			        response.setContentType("application/x-download;");
			        
			        response.setCharacterEncoding("UTF-8"); 
		            response.setHeader("Content-Length", String.valueOf(fileLength));  




顺便贴一下:各个浏览器关于request.getHeader("User-Agent"); 的输出内容: chrome : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36


FIREFOX:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0


IE8 : Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.3; .NET4.0C; .NET4.0E)


IE9 : Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)


IE10 : Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:10.0) like Gecko


IE11 : Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko


360 极速模式:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36


360 的IE9模式:Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)