struts2文件下载的中文名解决方案

来源:互联网 发布:php分页详解 编辑:程序博客网 时间:2024/06/05 04:00

找了很多资料,最后从论坛上找到的解决方案,这里贴一下几处关键代码

<action name="filedownload" class="fileDownloadAction">    <result name="success" type="stream">        <param name="contentType">application/octet-stream;charset=ISO8859-1</param> //注意这里的charset要写        <param name="contentDisposition">attachment;filename="${fileName}"</param>        <param name="inputName">downloadFile</param>    </result></action>
如果要通过url传递要下载的文件名,则要将要下载的中文名用URLEncoder编码:
ServletActionContext.getRequest().setAttribute("report",URLEncoder.encode(“我是中文.txt”, "utf-8"));

得到的是字符串。将此字符串传给url:

<a href="student/filedownload?fileName=${report}">
在下载文件的action中修改这几处
public InputStream getDownloadFile() throws Exception {    fileName = new String(fileName.getBytes("ISO-8859-1")); //将编码后的中文名解码,得到fileName为“我是中文.txt”
由于struts配置文件中<param name="contentDisposition">attachment;filename="${fileName}"</param>获取的filename="${fileName}"是通过getFileName()方法获取的。因此修改getFileName()方法:
public String getFileName() throws Exception {    return new String(fileName.getBytes(), "ISO8859-1");}
至此,下载的文件中文名问题解决。

0 0
原创粉丝点击