1:Stream
<result-type name="stream" class="org.apache.struts2.result.StreamResult"/>
A custom Result type for sending raw data (via an InputStream) directly to the HttpServletResponse. Very useful for allowing users to download content.
This result type takes the following parameters:
- contentType - the stream mime-type as sent to the web browser (default = text/plain).
- contentLength - the stream length in bytes (the browser displays a progress bar).
- contentDisposition - the content disposition header value for specifing the file name (default = inline, values are typically attachment;filename="document.pdf".
- inputName - the name of the InputStream property from the chained action (default = inputStream).
步1:开发一个action,提供一个getInputStream():InputStream
public class DownAction extends ActionSupport {
@Override
public String execute() throws Exception {
System.err.println("判断用户的积分,判断用户的状态..");
return SUCCESS;
}
public InputStream getInputStream() throws Exception {
String path = ServletActionContext.getServletContext().getRealPath("/files/yy.zip");
InputStream in = new FileInputStream(path);
return in;
}
}
步2:配置到stuts.xml中且返回的<result type=”stream”/>
<action name="down" class="cn.down.DownAction">
<result type="stream"></result>
</action>
<action name="down" class="cn.down.DownAction">
<result type="stream">
<param name="contentType">application/force-download</param>
<param name="contentDisposition">attachment;filename="document.zip"</param>
</result>
</action>
附加:
1:下载时修改名称
String name = "我的文件.zip";
name = URLEncoder.encode(name,"UTF-8");
ActionContext.getContext().put("fileName", name);
在XML中取值:
在XML中使用OGNL取值,是通过${..}
<action name="down" class="cn.struts2.down.DownAction">
<result type="stream">
<param name="contentType">application/force-download</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
</result>
</action>
--通过inputName指定方法名:
<action name="down" class="cn.struts2.down.DownAction">
<result type="stream">
<param name="contentType">application/force-download</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 在DownAction.getDownfile():InputStream -->
<param name="inputName">downfile</param>
</result>
</action>
public InputStream getDownfile() throws Exception {
String path = ServletActionContext.getServletContext().getRealPath("/files/yy.zip");
InputStream in = new FileInputStream(path);
return in;
}