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>