第一步:struts.xml的配置
<action name="downLoad" class="downloadAction" method="downLoad">
<!-- 配置結果類型爲stream的結果 -->
<result name="success" type="stream">
<!-- 指定下載文件的類型 -->
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
<!--指定被下載文件名 -->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 指定下載文件的位置 -->
<param name="inputName">downloadFile</param>
</result>
</action>
第二步:實現下載的Action代碼
public class DownloadActionimplements Action{
private String fileName;
public String downLoad() throws Exception{
return SUCCESS;
}
//下載用的Action應該返回一個InputStream實例
//該方法對應在result裏的inputName屬性值爲downloadFile
public InputStream getDownloadFile() throws Exception {
InputStream in=ServletActionContext.getServletContext().getResourceAsStream("/_upload/test.zip");
return in;
}
//該屬性石依賴注入的屬性,可以在配置文件中動態指定該屬性
public String getFileName() {
String name = "test.zip";
String userAgent = getRequest().getHeader("User-Agent");
if(userAgent.indexOf("MSIE") > 0 || userAgent.indexOf("rv:11.0") > 0){
return new String(name.getBytes("gb2312"), "iso-8859-1");
} else {
return new String(name.getBytes("UTF-8"), "iso-8859-1");
}
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
第三步:下載文件
<a href="downLoad.action">下載</a>