java web上传下载乱码问题解决方法

文件下载中文乱码,因为http请求url和header要求只能通过ascii码,对于其他字符则不行,需要转码。而不同浏览器的处理方式右不一样。

解决方法一:

	/**
	 * 乱码解决
	 * @throws UnsupportedEncodingException 
	 * */
	private static String toUtf8BytesString(String fileName, HttpServletRequest req) throws UnsupportedEncodingException {
		//return new String(fileName.getBytes("GBK"), "ISO8859-1");
		if(req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
			return URLEncoder.encode(fileName, "UTF-8");
		}else{
			return new String(fileName.getBytes("UTF-8"), "ISO8859-1");
		}
	}

解决方法二:

  这种方法在 windows 中文系统新版firefox、ie、chrome下下载不会乱码,不知道其他系统默认字符集非gbk的会不会有问题

new String(fileName.getBytes("gbk"), "ISO8859-1")

 参考资料:

http://www.ruanyifeng.com/blog/2010/02/url_encoding.html

  

原文地址:https://www.cnblogs.com/xunux/p/4447121.html