1 package cn.temp; 2 3 import java.io.FileInputStream; 4 import java.io.InputStream; 5 import java.net.URLEncoder; 6 7 import org.apache.struts2.ServletActionContext; 8 9 import com.opensymphony.xwork2.ActionContext; 10 import com.opensymphony.xwork2.ActionSupport; 11 12 public class ThreeAction extends ActionSupport { 13 // 1: 开发execute方法,如果execute方法正常执行成功,则返回successs/down 14 // 只有返回string以后才会去下载 15 @Override 16 public String execute() throws Exception { 17 System.err.println("判断用户的积分..."); 18 //对名称进行编码 19 String str = "倒霉.mp4"; 20 str = URLEncoder.encode(str, "UTF-8"); 21 ActionContext.getContext().put("name", str); 22 return "down"; 23 } 24 25 // 2:如果返回到了<result name="down" type="stream"/> 26 // 此时就会开始调用getInputSteam方法获取文件的二进制数据 27 public InputStream getFile() throws Exception { 28 String path = ServletActionContext.getServletContext().getRealPath("/files/dmx1.mp4"); 29 InputStream in = new FileInputStream(path); 30 return in; 31 } 32 }
struts xml文件配置
<!-- 配置下载 --> <action name="three" class="cn.temp.ThreeAction"> <result name="down" type="stream"> <param name="contentType">application/force-download</param> <param name="contentDisposition">attachment;filename=${name}</param> <!-- 指定哪一个方法可以获取二进制数据,则在类中,必须要有一个应运getFile():InputStream --> <param name="inputName">file</param> </result> </action>
inputname 默认是InputStream