Struts2文件下载实例 图片看不了?点击切换HTTP 返回上层
通过《Struts2文件下载简介》教程的学习,读者已经了解了使用 Struts2 框架实现在指定的目录中下载指定文件的功能。下面通过案例演示文件下载功能。
1)创建下载页面
在 struts2Demo06 项目的 WebContent 目录下创建一个名称为 download.jsp 的页面文件,在文件中添加一个用于文件下载的链接,其主要代码如下所示:<s:a href="simpledownload?filename=test.txt" name="test">test.txt</s:a>
2)创建 Action
在 com.mengma.action 包中新建一个名称为 SimpleDownLoadAction 的类,该类主要用于处理文件下载的核心操作,其代码如下所示。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | package com.mengma. action ; import java.io.InputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class SimpleDownLoadAction extends ActionSupport { private String filename; public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } // 定义了返回InputStream的方法,该方法作为被下载文件的入口 public InputStream getDownloadFile() { // 获取下载文件名称 String filename = ServletActionContext.getRequest().getParameter( "filename" ); // 定义下载文件路径 String filePath = "/upload/" + filename; // 返回一个流对象 return ServletActionContext.getServletContext().getResourceAsStream( filePath); } } |
3)编写配置文件信息
在 struts.xml 中增加 action 的配置,其代码如下所示:1 2 3 4 5 6 7 8 9 10 11 12 | < action name = "simpledownload" class= "com.mengma.action.SimpleDownLoadAction" > <result type= "stream" > <! --文件类型 --> <param name = "contentType" >text/plain</param> <! --指定文件名 --> <param name = "contentDisposition" > attachment;filename=${filename} </param> <! --输入流 --> <param name = "inputName" >downloadFile</param> </result> </ action > |
4)运行项目并查看结果
启动项目后,在浏览器的地址栏中输入地址 http://localhost:8080/struts2Demo06/download.jsp,即可显示如图 1 所示的页面。
图 1 下载页面
单击下载页面的超链接后,浏览器的显示结果如图 2 所示。

图 2 上传页面