一 struts.xml文件的编辑
<struts>
<package name="crud-default" extends="convention-default">
<action name="download" class="com.myweb.download.DownLoadAction">
<!--type 为 stream 应用 StreamResult 处理-->
<result name="success" type="stream">
<!--默认为 text/plain-->
<param name="contentType">application/x-msdownload;charset=ISO8859-1</param>
<!-- 默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,
比如这里就是 getInputStream() 来获取下载文件的内容,意味着你的 Action 要有这个方法 -->
<param name="inputName">inputStream</param>
<!-- 默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename
指定下载文件时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名 -->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 输出时缓冲区的大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>
二,com.myweb.download.DownLoadAction 的文件的代码
public class DownLoadAction extends ActionBase {
private Logger logger = LoggerFactory.getLogger(DownLoadAction.class);
private String fileName = null;
public String execute() throws Exception {
return "success";
}
public InputStream getInputStream() {
this.fileName = json.substring(json.lastIndexOf("\\") + 1, json.length());
return Struts2Utils.getSession().getServletContext().getResourceAsStream(json);
}
public String getFileName() {
try {
Struts2Utils.getResponse().setHeader("charset","ISO8859-1");
return new String(this.fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "获取文件名出现了错误!";
}
}
}