Struts2文件下载

来源:互联网 发布:阿里云agent插件离线 编辑:程序博客网 时间:2024/04/29 08:09

文件下载先给出一个超链接到下载的Action,这个作为下载文件在webContent目录下:给出超链接为:

<a href="down?res=算法范围.doc&resType=application/msword&resName=my.doc">下载DOC类型文件</a>

参数以此为:文件名,文件类型,下载时的文件名;

下载文件需要在Struts配置文件中这样配置:

       <action name="down" class="struts1.action.DownAction">       <result type="stream" name="success">       <!-- 该参数指定二进制流 -->       <param name="contentType">${resType}</param>       <!-- 指定IO流的入口 -->       <param name="inputName">target</param>       <!-- 指定下载时文件名 -->       <param name="contentDisposition">filename=${resName}</param>       <!-- 指定缓冲大小 -->       <param name="bufferSize">4096</param>       </result>       </action>

相应的Action类的写法为:

public class DownAction extends ActionSupport {//下载文件主要有三种:1、下载的目标资源,2、下载文件类型,3、下载文件名private String res;//下载目标资源private String resType;//下载文件类型private String resName;//下载文件名//下载文件IO流的入口public InputStream getTarget() throws IOException {String path = ServletActionContext.getServletContext().getRealPath("/");return new FileInputStream(path+res);}public String getRes() {return res;}public void setRes(String res) throws Exception{//对请求参数做处理this.res = new String(res.getBytes("ISO-8859-1"), "UTF-8");}public String getResType() {return resType;}public void setResType(String resType) {this.resType = resType;}public String getResName() {return resName;}public void setResName(String resName) {this.resName = resName;}}
这个是通用的Struts2下载模板

原创粉丝点击