作者: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 { /* * 对fileName参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码。 * 这里使用request.setCharacterEncoding解码无效. * 只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件 * */ String str=new String(fileName.getBytes("ISO8859-1"),"utf-8"); this.fileName=str; } /** * @getFileName * 此方法对应的是struts.xml文件中的: * <param >attachment;filename="${fileName}"</param> * 这个属性设置的是下载工具下载文件时显示的文件名, * 要想正确的显示中文文件名,我们需要对fileName再次编码 * 否则中文名文件将出现乱码,或无法下载的情况 * @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 * 此方法的命名是有规定的,对应的是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); } @Override public 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>
页面调用:
如:
<a href="base/downloadAction.do?relativePath=/userfiles/branchComInvWeekly&fileName=济南20110531184126875.xls">下载</a>