实现文件下载的FileDownloadAction:提供一个返回InputStream流的方法。
DownAction.java
package action; import java.io.InputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class DownAction extends ActionSupport{ /** * 定义一个返回InputStream的方法, 该方法将作为被下载文件的入口, 且需要配置stream类型结果时指定inputName参数, inputName参数的值就是方法去掉get前缀、首字母小写的字符串 */ private static final long serialVersionUID = 1L; private String inputPath;//该属性可以在配置文件中动态指定该属性值 public InputStream getTargetFile() throws Exception { return ServletActionContext.getServletContext().getResourceAsStream(inputPath);//ServletContext提供getResourceAsStream()方法 //返回指定文件对应的输入流 } public void setInputPath(String value) {//依赖注入该属性值的setter方法 inputPath = value; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘down.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <a href="/Upload-1/uploadFiles/xia.png">123</a> <a href="/Upload-1/uploadFiles/中文.png">中文</a> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="hello" namespace="/hello" extends="struts-default"> <action name="down" class="action.DownAction"> <param name="inputPath">\uploadFiles\xia.png</param> <result name="success" type="stream"> <param name="contentType">image/x-png</param> <param name="inputName">targetFile</param> <param name="bufferSize">600000</param> <param name="contentDisposition">filename="小.jpg"</param> </result> </action> </package> </struts>
原文:http://blog.csdn.net/yantingmei/article/details/20300111