struts2文件下载及文件名中文问题

1. struts2配置文件:

<result name="testsuccess" type="stream">
<!-- 声明下载时存储文件流的变量名 -->
<param name="inputName">testStream</param>
<param name="contentType">application/octet-stream;charset=GBK</param>
<!-- fileName 为Action类中定义的私有变量,用于存储下载文件时显示的文件名 -->
<param name="contentDisposition">
attachment;filename="${fileName}"
</param>
<param name="bufferSize">4096</param>
</result>

说明:

result标签中需要定义 type=”stream” 。

在Action中只需要定义 testStream 的get方法即可,即getTestStream(),不需要定义private InputStream testStream这样的类私有变量。

2.Action中:

@Controller("downloadAction")
@Scope("prototype")
public class DataDownloadAction extends ActionSupport {
    //用户存储下载时显示的文件名
    private String fileName;
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public InputStream getTestStream() throws Exception {
        String filename = "中文书名测试.pdf";
        String filepath = "E:\\book\\"+filename;
        File file = new File(filepath);
        InputStream inStream = null;
        inStream = new FileInputStream(file);
        //需要转换才可以显示中文文件名
        this.fileName = new String(filename.getBytes(), "ISO8859-1");
        return inStream;
    }
}

说明:

如果文件名为中文,需要在给fileName定义时进行字符集转换:this.fileName = new String(filename.getBytes(), “ISO8859-1”);

此外,tomcat的字符集需要设置为UTF-8,具体方法为编辑conf/server.xml中添加URIEncoding=”UTF-8”

<Connector port="8080" protocol="HTTP/1.1" 
maxThreads="150" connectionTimeout="20000" 
redirectPort="8443" URIEncoding="UTF-8"/>

posted on 2015-12-07 13:48  码农康康  阅读(195)  评论(0编辑  收藏  举报

导航