struts2多文件动态下载及中文解决方案
作者:yan?
?
Action代碼:
package com.xxx.base.view.action; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import com.ruizcon.base.util.MyException;public class DownloadAction extends BaseAction {private String fileName;private String relativePath;public void setFileName(String fileName) throws UnsupportedEncodingException {/** 對(duì)fileName參數(shù)進(jìn)行UTF-8解碼,注意:實(shí)際進(jìn)行UTF-8解碼時(shí)會(huì)使用本地編碼。* 這里使用request.setCharacterEncoding解碼無(wú)效.* 只有解碼了getDownloadFile()方法才能在下載目錄下正確找到請(qǐng)求的文件* */String str=new String(fileName.getBytes("ISO8859-1"),"utf-8");this.fileName=str;}/*** @getFileName* 此方法對(duì)應(yīng)的是struts.xml文件中的:* <param >attachment;filename="${fileName}"</param>* 這個(gè)屬性設(shè)置的是下載工具下載文件時(shí)顯示的文件名,* 要想正確的顯示中文文件名,我們需要對(duì)fileName再次編碼* 否則中文名文件將出現(xiàn)亂碼,或無(wú)法下載的情況* @return* @throws UnsupportedEncodingException* @author XieYanZhou(Yan)* @date 2011-6-1* @version v1.0*/public String getFileName() throws UnsupportedEncodingException{String str= new String(fileName.getBytes(), "ISO8859-1");return str;}public void setRelativePath(String relativePath) throws UnsupportedEncodingException {//this.relativePath = relativePath;String str=new String(relativePath.getBytes("ISO8859-1"),"utf-8");this.relativePath=str;}/*** * @getDownloadFile* 此方法的命名是有規(guī)定的,對(duì)應(yīng)的是struts.xml文件中的:* <param >downloadFile</param>* 返回下載文件的流,可以參看struts2的源碼* @return* @author XieYanZhou(Yan)* @date 2011-6-1* @version v1.0*/public InputStream getDownloadFile(){/*String baseRealPath=this.getSession().getServletContext().getRealPath("");String path = baseRealPath + relativePath + "//" + this.fileName;path=path.replaceAll("/", "");FileInputStream fis = new FileInputStream(path);return fis;*/return this.getServletContext().getResourceAsStream(relativePath +"/"+ fileName);}@Overridepublic String execute() throws Exception {return SUCCESS;}} ?
?
xml配置:
<action name="downloadAction" class = "downloadAction"><result name="success" type="stream"><!-- <param name="contentType">application/excel,application/vnd.ms-excel</param> --><param name="contentDisposition">attachment;filename="${fileName}"</param><param name="inputName">downloadFile</param><param name="bufferSize">4096</param></result></action>?
?
頁(yè)面調(diào)用:
如:
<a href="base/downloadAction.do?relativePath=/userfiles/branchComInvWeekly&fileName=濟(jì)南20110531184126875.xls">下載</a>
總結(jié)
以上是生活随笔為你收集整理的struts2多文件动态下载及中文解决方案的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 运行velocity的官方例子
- 下一篇: lua相关链接