---
title: "Struts2文件下载中文名乱码解决方法"
author: "robindut"
date: "2012-04-27T15:19:50Z"
tags: []
categories: ["Web前端"]
slug: "struts2"
draft: false
lastmod: "2012-04-27T15:24:22Z"
id: 1501822
url: "https://robindut.iteye.com/blog/1501822"
---

最近使用Sturts2作文件下载时，发现在不同的浏览器上会有中文文件名乱码的问题，现在把解决方法放在这里，以便留个备份。

 

struts2配置文件如下:

 

```
<action name="fileDownLoad" class="com.test.FileDownloadAction">
			<result name="download" type="stream">
				<param name="contentType">application/pdf;charset=UTF-8</param>
				<param name="contentDisposition">attachment;filename="${filename}.pdf"</param>
				<param name="inputName">inputStream</param>
				<param name="bufferSize">4096</param>
			</result>
		</action>
```

 

 FileDownloadAction.java的文件名处理的 代码如下(其他代码忽略)：

 

```
/**
	 * 下载文件名编码，对于不同的浏览器使用不同的编码格式
	 * 
	 * @param request 
	 * @param name
	 */
	private String processFileName(HttpServletRequest request, String name)
			throws UnsupportedEncodingException {
		String filename = null;
		String agent = request.getHeader("USER-AGENT");
		if (null != agent){
			if (-1 != agent.indexOf("Firefox")) {//Firefox
				filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(name.getBytes("UTF-8"))))+ "?=";
			}else if (-1 != agent.indexOf("Chrome")) {//Chrome
				filename = new String(name.getBytes(), "ISO8859-1");
			} else {//IE7+
				filename = java.net.URLEncoder.encode(name, "UTF-8");
				filename = StringUtils.replace(filename, "+", "%20");//替换空格
			}
		} else {
			filename = name;
		}

		return filename;
	}
```

网上很多说直接使用"ISO8859-1"编码格式的问题，经过验证并不能很好的解决问题，还是需要对于不同的浏览器使用不同的编码格式，浏览器兼容性的问题真心纠结。。。

注：这里只选取了三种主流浏览器(ie7+，firefox8.0，chrome18.0)，其他浏览器未作测试。