struts2 文件下载

struts2文件下载,想的复杂,实际上简单的你都想不到有那么简单

Action

复制代码
package cn.luxh.struts2.action;
 
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts2.ServletActionContext;
 
import com.opensymphony.xwork2.ActionSupport;
 
 
/**
 * 文件下载
 * @author Luxh
 */
public class DownloadAction extends ActionSupport {
//文件名
    private String fileName;
private String inputPath;
public String getFileName() { return fileName; } public void setFileName(String fileName) throws UnsupportedEncodingException { //用UTF-8重新编码文件名,解决中文乱码 this.fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8"); }
public InputStream getInputStream() throws UnsupportedEncodingException, FileNotFoundException{
      //attachment,以附件的方式下载文件,会打开保存文件对话框;inline,以内联的方式下载,浏览器会直接打开文件


     HttpServletResponse response
= ServletActionContext.getResponse(); response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(fileName,"UTF-8"));//java.net.URLEncoder.encode(fileName,"UTF-8") 编码转换,解决乱码 //如果fileName是相对路径 //return ServletActionContext.getServletContext().getResourceAsStream(inputPath); //如果fileName是绝对路径 return new BufferedInputStream(new FileInputStream(inputPath)); } @Override public String execute() throws Exception { return SUCCESS; }

    public String getInputPath() {
      return inputPath;
    }
    public void setInputPath(String inputPath) {

      this.inputPath = inputPath;
    }

}
复制代码

struts.xml配置文件

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
 
<struts>
    <package name="download" namespace="/download" extends="default">
         
         <action name="download" class="cn.luxh.struts2.action.DownloadAction">
            <result name="success" type="stream">
                 <!-- 下载文件类型定义 -->
                 <param name="contentType">application/octet-stream</param>
                 <!-- 下载文件输出流定义 -->
                 <param name="inputName">inputStream</param><br>                  <span><!-- 下载文件处理方式 --> </span><br><span>                <param name="contentDisposition">attachment;filename="${fileName}"</param></span>
                 <!-- 下载文件的缓冲大小 -->
                 <param name="bufferSize">4096</param>
            </result>
        </action>
         
    </package>
</struts>
复制代码

jsp

<a href="....action?inputPath=...fileName=...">下载</a>

 

总结:sturts2文件下载

Action:1.从jsp得到文件的路径以及文件名称

    2.写一个返回InputStream的方法(按照绝对路径和相对路径有所不同)

        相对路径:return ServletActionContext.getServletContext().getResourceAsStream(inputPath);

        绝对路径:return new BufferedInputStream(new FileInputStream(inputPath));

    3.execute方法(或者其他方法)都不用处理,只需要返回一个字符串就可以了

struts.xml:1.result的type是stream注意

      2.在result里通过标签<param></param>配置contentType,inputName,burrerSize

jsp:就只负责传参数就可以了

 

 

 

 

 

 

多个文件下载

 2、处理多个附件下载的Action。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package cn.luxh.struts2.action;
 
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import cn.luxh.utils.ZipFileUtil;
 
import com.opensymphony.xwork2.ActionSupport;
 
/**
 * 处理多个附件下载
 * @author Luxh
 */
public class MultiFileDownloadAction extends ActionSupport {
 
    private static final long serialVersionUID = 2743077909387361587L;
     
    //接收JSP页面传递过来的附件的路径
    private String attachmentPath;
     
    //最终压缩后的zip文件的路径,传递给通用的下载Action
    private String fileName;
 
     
    /**
     * 下载多个附件
     * 实现:将多个附近压缩成zip包,然后再下载zip包
     */
    public String downloadMultiFile() {
        //使用当前时间生成文件名称
        String formatDate =new  SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        //压缩后的zip文件存放路径
        fileName = "D:/test/" + formatDate + ".zip";
         
        if(attachmentPath != null && !"".equals(attachmentPath)) {
            //将多个附件的路径取出
            String[] attachmentPathArray = attachmentPath.split(",");
            if(attachmentPathArray != null && attachmentPathArray.length >0) {
                File[] files = new File[attachmentPathArray.length];
                for(int i=0;i<attachmentPathArray.length;i++) {
                    if(attachmentPathArray[i] != null) {
                        File file = new File(attachmentPathArray[i].trim());
                        if(file.exists()) {
                            files[i] = file;
                        }
                    }
                }
                //将多个附件压缩成zip
                ZipFileUtil.compressFiles2Zip(files,fileName);
            }
             
        }
        return SUCCESS;
    }
     
     
    public String getAttachmentPath() {
        return attachmentPath;
    }
    public void setAttachmentPath(String attachmentPath) {
        this.attachmentPath = attachmentPath;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
     
     
 
}

  Action中的压缩文件类ZipFileUtil参考 http://www.cnblogs.com/luxh/archive/2012/06/28/2568758.html

  配置文件:

 

1
2
3
4
5
6
7
8
9
<!--将多个附件压缩后重定向到公共的下载Action下载文件  -->
        <action name="downloadMultiFile" class="cn.luxh.struts2.action.MultiFileDownloadAction" method="downloadMultiFile">
           <result type="redirectAction">
               <param name="actionName">download</param>
               <param name="nameSpace">/download</param>
               <!--附件的完整路径  -->
               <param name="fileName">${fileName}</param>
           </result>
       </action>

  3、附件列表展现的JSP页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
    <head>
    <title>File Download</title>
     
    <meta http-equiv="description" content="error">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
     
    <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        function checkFile() {
            if($("#all").attr("checked")){
                $("input[name='attachmentPath']").attr("checked",true);
            }else {
                $("input[name='attachmentPath']").attr("checked",false);
            }
        }
         
    </script>
    </head>
 
    <body>
     
        <form  action="${pageContext.request.contextPath}/index/downloadMultiFile" method="post">
            <table>
                 <tr>
                     <th>
                            <input type="checkbox" name="all" id="all" onchange="checkFile()">全选
                     </th>
                      <th>
                            文件名
                     </th>
                      <th>
                            文件路径
                     </th>
                      <th>
                            下载
                     </th>
                 </tr>
                <c:forEach items="${attachmentList}" var="attachment">
                    <tr>
                        <td>
                            <input type="checkbox" name="attachmentPath" value="${attachment.filePath}">
                        </td>
                        <td>${attachment.fileName}</td>
                        <td>${attachment.filePath}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/download/download?fileName=${attachment.filePath}">下载</a>
                        </td>
                    </tr>
                </c:forEach>
            </table>
            <tr>
                <td>
                    <input type="submit" value="下载所选文件" id="submit">
                </td>
            </tr>
        </form>
         
    </body>
</html>

 

 

 

 

 attachmentList是后台传过来的一个存放附件信息的List.

1、一个封装附件信息的实体Attachment。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 * 附件信息
 */
public class Attachment {
     
    private Integer id;
    //附件名称
    private String fileName;
    //附件路径
    private String filePath;
     
    //get set 方法   
     
     
 
}


2、在Action中查出附件信息,存放到List中。

1
2
3
4
5
6
7
8
9
10
/**
     * 显示附件下载列表
     */
    public String showAttachmentList() {
        //从数据库中查找出附件信息
        List<Attachment> attachmentList = attachmentService.getAllAttachments();
        //将附件信息列表存放起来,在页面就可以获取到
        ActionContext.getContext().put("attachmentList", attachmentList);
        return SUCCESS;
    }



3、在页面就可以迭代attachmentList把附件信息展现出来了。

4、附件实体Attachment中存放有附件的路径filePath,将filePath传到下载Action就可以了。要注传的是绝对路径还是相对路径。

<a href="${pageContext.request.contextPath}/download/download?fileName=${attachment.filePath}">下载</a> 中的fileName=${attachment.filePath}就是将附件路径传给下载的Action

希望可以帮到你。

posted @ 2014-05-06 11:04  刘尊礼  阅读(214)  评论(0)    收藏  举报