struts2文件下载(解决中文文件名问题)

1.首先,jsp页面进行下载的那段话需要使用<s:url>标签:

1 <a href="<s:url value='filedownload.action'>                 
2                     <s:param name='fileName' >无线网络.ppt</s:param>
3             </s:url>">
4             下载文件
5     </a>

2.struts2.xml文件中的配置:

 1 <action name="filedownload" class="Action.FileUploadAction" method="downloadfile">
 2             <param name="fileName"></param>  
 3             <result name="success" type="stream">
 4                <param name="contentType">application/vnd.ms-powerpoint</param>
 5                <param name="contentDisposition">
 6                     attachment;filename="${dnfileName}" 
 7                 </param> 
 8                <param name="inputName">downloadFile</param>
 9             </result>
10 
11         </action>

这里解释一下:fileName是前台jsp传过来的参数,dnfileName是显示给下载用户看文件名的参数,在Action中初始化(因为如果文件名是中文的话,显示给用户会乱码,所以我直接把显示给用户看的设为当前时期+时间),<param name="inputName">downloadFile</param>这一句是意思代表Action中下载文件的方法名为getDownloadFile().

最后,看看Action中的相应代码:

View Code
 1         private String fileName;
 2         private String dnfileName;
 3         public String getFileName() {
 4         return fileName;
 5     }
 6     public void setFileName(String fileName) {
 7         this.fileName = fileName;
 8     }
 9     public String getDnfileName() {
10         return dnfileName;
11     }
12     public void setDnfileName(String dnfileName) {
13         this.dnfileName = dnfileName;
14     }
15         public String downloadfile() throws Exception {
16         fileName = new String(fileName.getBytes("iso-8859-1"),"gbk");  
17         System.out.println("fn="+fileName);
18         Date d = new Date();
19         dnfileName = (new SimpleDateFormat("yyyyMMddkkmmss").format(d)) + "." + (fileName.split("\\."))[1];
20          return "success";
21      }
22     
23     public InputStream getDownloadFile() throws UnsupportedEncodingException{
24         System.out.println("fn2="+fileName);
25         return ServletActionContext.getServletContext().getResourceAsStream("/upload/"+fileName);
26         
27     }    

 

posted on 2013-01-19 15:25  saobchj  阅读(3175)  评论(1编辑  收藏  举报

导航