Struts2通过org.apache.struts2.dispatcher.StreamResult结果类型来支持文件下载,重要属性:
contentType:用来指定下载文件的类型,application/octet-stream表示无限制。
inputName:流对象名,严格遵守JavaBean规范,它对应着Action中返回InputStream类型的方法名,假如inputName的值为downFile,则Action中必定有一个public InputStream getDownFile()方法。
contentDisposition:可以设定两个值,它的第一个值来设定文件打开方式,默认是inline即在浏览器中打开,也可以设定attachment(附件的形式),第二个值格式为filename="${fileName}",第二个值也严格遵守JavaBean规范,假设符号内的值为fileName,则Action中必定有一个public String getFileName()方法。
bufferSize:下载文件的缓冲区大小。
DownTestAction.java:
public class DownTestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
/*要下载的文件名*/
private String fileName = null;
/*文件保存的路径(在struts.xml文件中注入)*/
private String path;
public String getPath() {
return path;
}
public void setPath(String path){
this.path = path;
}
public String getFileName() {
try {
//在服务器端通过设置http Header, 设置了客户端的默认的字符集编码
ServletActionContext.getResponse().setHeader("charset", "ISO8859-1");
return new String(this.fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "获取文件名出现错误!";
}
}
public void setFileName(String fileName){
this.fileName = fileName;
}
/**
* 下载方法
* @return
* @throws FileNotFoundException
*/
public InputStream getInputStream() throws FileNotFoundException {
/* 创建文件 */
File file = new File(this.path + this.fileName);
/* 创建文件输入流 */
InputStream stream = new FileInputStream(file);
return stream;
}
}
struts.xml:
<action name="downTestAction" class="com.lixue.web.action.DownTestAction">
<!-- 通过注入的方式指定文件的路径 -->
<param name="path">D:/</param>
<!--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>
下载页download.jsp:
<body>
<a href="downTestAction.action?fileName=web.txt">下载</a>
</body>