Struts2 动态压缩成zip文件下载

来源:互联网 发布:sql统计每小时数据 编辑:程序博客网 时间:2024/06/14 23:00
功能:文件下载 
简述: 
1.根据画面上的复选框进行文件打包下载 
2.待下载文件保存在服务器的硬盘上,打包过程中不生成临时文件 
3.打包过程中需要动态创建一个txt文件一并打进zip包中 
4.页面上没有文件被选择的场合,按下【下载】按钮后,什么都不做(不刷新页面) 

部分内容参考自互联网,如果错误,欢迎指正。 

Struts配置文件 
1<!-- 数据下载Action -->
2<action name="downloadWaveData" class="DownloadAction">
3    <result name="nodata" type="httpheader">
4        <param name="status">204</param>
5    </result>
6</action>


Action代码 
查看源码
打印?
01private OutputStream res;
02private ZipOutputStream zos;
03 
04// action的主方法
05public String execute() throws Exception {
06     
07    if (有数据可下载) {;
08        // 预处理
09        preProcess();
10 
11    else {
12        // 没有文件可下载的场合,返回nodata,设定参照struts配置文件
13        return "nodata";
14    }
15 
16    // 在这里编辑好需要下载的数据
17    // 文件可以是硬盘上的
18    // 文件也可以是自己写得数据流,如果是自己写得数据流,请参看outputZipFile方法中的【2.】
19    File file = new File();
20    file = ...
21    outputZipFile(file);
22     
23    // 后处理
24    afterProcess();
25     
26    return null;
27 
28}
29 
30// 预处理
31public void preProcess() throws Exception {
32     
33    HttpServletResponse response = ServletActionContext.getResponse();
34     
35    res = response.getOutputStream();
36 
37    //清空输出流
38    response.reset();  
39 
40    //设定输出文件头
41    response.setHeader("Content-disposition ","attachment; filename=a.zip ");  
42    response.setContentType("application/zip");
43    zos = new ZipOutputStream(res);
44     
45}
46 
47// 后处理
48public void afterProcess() throws Exception {
49    zos.close();
50    res.close();
51}
52 
53// 写文件到客户端
54private void outputZipFile(File file) throws IOException, FileNotFoundException {
55    ZipEntry ze = null;
56    byte[] buf = new byte[1024];
57     
58    int readLen = 0;
59     
60    File file = (File)fileList.get(i);
61     
62    // 1.动态压缩一个File到zip中
63    // 创建一个ZipEntry,并设置Name和其它的一些属性
64    // 压缩包中的路径和文件名称
65    ze = new ZipEntry("1\\1" + f.getName());
66    ze.setSize(file.length());
67    ze.setTime(file.lastModified());
68 
69    // 将ZipEntry加到zos中,再写入实际的文件内容
70    zos.putNextEntry(ze);
71    InputStream is = new BufferedInputStream(new FileInputStream(file));
72 
73    // 把数据写入到客户端
74    while ((readLen = is.read(buf, 01024)) != -1) {
75        zos.write(buf, 0, readLen);
76    }
77    is.close();
78     
79    // 2.动态压缩一个String到zip中
80    String customFile = "This is a text file.";
81 
82    // 压缩包中的路径和文件名称
83    ZipEntry cze = new ZipEntry(“1\\1\\” + "Test.txt");
84    zos.putNextEntry(cze);
85 
86    // 利用ByteArrayInputStream把流数据写入到客户端
87    is = new ByteArrayInputStream(customFile.getBytes());
88    while ((readLen = is.read(buf, 01024)) != -1) {
89        zos.write(buf, 0, readLen);
90    }
91     
92}
扎客小站:www.ezhake.com
原创粉丝点击