1.web.xml配置還是一樣
2.file.jsp頁面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>下載文件</title>
</head>
<body>
下載文件
<br>
test.txt<a href="downloadFile.action?number=1">下載1</a>
<br>
二級緩存 ehcache.jsp<a href="downloadFile.action?number=2">下載2</a>
</body>
</html>
3.FileAction.java
private int number;//
private String fileName;//get和set方法省略
/**
* 文件下載
* 鄭平
* @return
* 2014-7-23
*/
public InputStream getLoadFile(){
System.out.println("文件下載+++++++++++");
if(1 == number){
this.fileName = "test.txt" ;
//獲取資源路徑
return ServletActionContext.getServletContext().getResourceAsStream("upload/test.txt");
}else if(2 == number){
this.fileName = "二級緩存ehcache.jsp";
//解解亂碼
try {
this.fileName = new String(this.fileName.getBytes("GBK"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ServletActionContext.getServletContext().getResourceAsStream("upload/二級緩存 ehcache.jsp") ;
}
else
return null ;
}
下載路徑,彷彿只能在tomcat更目錄裏面下載。例如:在WebContent下面新建一個文件夾->upload裏面有文件1.test.txt;2.二級緩存 ehcache.jsp;
3.配置file.xml
<action name="downloadFile" class="com.file.action.FileAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="contentDisposition">attachment;fileName="${fileName}"</param>
<param name="inputName">loadFile</param>
<param name="bufferSize">1024</param>
</result>
<result name="input">/default.jsp</result>
</action>
<param name="contentType">application/octet-stream</param> 所有類型文件
<param name="inputName">loadFile</param> //loadFile 是FileAction.java中的getLoadFile方法對應的
<param name="contentDisposition">attachment;fileName="${fileName}"</param>
//fileName="${fileName} 是下載該文件時,顯示文件的名稱
4.struts.xml配置
<include file="com/struts/config/file.xml"></include>