1.在action中定义变量

1
2
3
4
5
6
private List<String> downLoadPaths = new ArrayList<String>();//存储选中文件的下载地址
private OutputStream res;
private ZipOutputStream zos;
private String outPath;
private String lessionIdStr;// 选中文件ID拼接的字符串
private String fileName; //浏览器下载弹出框中显示的文件名

分别给出get和set方法

2.  主方法 

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
   * 下载多个文件:压缩成zip
   *
   * @return
   * @throws Exception
   */
  public String downLoadLessionsZip() {
    downLoadPaths.clear();
    String firstFileName = "";// 第一个文件的文件名
    List<DownLoadFileVo> fileVos = new LinkedList<DownLoadFileVo>();
    if (StringUtils.isNotEmpty(lessionIdStr)) {
      int end = lessionIdStr.lastIndexOf(",");
      if (end > 0) {
        if (end == lessionIdStr.length() - 1) {
          lessionIdStr = lessionIdStr.substring(0, end);
        }
        String[] ids = lessionIdStr.split(",");
        for (int i = 0; i < ids.length; i++) {
          if (StringUtils.isNumeric(ids[i])) {
            BkPersonLession lession = bkPersonLessionService.downLoadLession(Integer.parseInt(ids[i]));
            if (lession != null) {
              fileVos.add(new DownLoadFileVo(lession
                  .getLessionName(), getContextRealPath()
                  + lession.getLessionSavePath()));
              downLoadPaths.add(getContextRealPath()
                  + lession.getLessionSavePath());
            }
            if (i == 0) {              
                       firstFileName = lession.getLessionName();
            }
          }
        }
      }
    }
    // 有数据可以下载
    if (downLoadPaths.size() != 0) {
      // 进行预处理
      preProcess(firstFileName);
    } else {
      // 没有文件可以下载,返回nodata
      return "nodata";
    }
    // 处理
    writeZip(fileVos);
    // 后处理关闭流
    afterProcess();
    return null;
  }
  // 压缩处理
  public void writeZip(List<DownLoadFileVo> fileVos) {
    byte[] buf = new byte[8192];
    int len;
    for (DownLoadFileVo fileVo : fileVos) {
      File file = new File(fileVo.getFileSavePath());
      if (!file.isFile())
        continue;
      ZipEntry ze = new ZipEntry(fileVo.getFileName()
          + fileVo.getFileSavePath().substring(
              fileVo.getFileSavePath().lastIndexOf(".")));                          
      try {
        zos.putNextEntry(ze);
        BufferedInputStream bis = new BufferedInputStream(
            new FileInputStream(file));
        while ((len = bis.read(buf)) > 0) {
          zos.write(buf, 0, len);
        }
        bis.close();
        zos.closeEntry();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  // 预处理
  public void preProcess(String firseFileName) {
    String zipName = "【批量下载】" + firseFileName + "等.zip";
    String filename = "";
    try {
      filename = new String(zipName.getBytes("GBK"), "8859_1");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    this.fileName = filename;
    HttpServletResponse response = ServletActionContext.getResponse();
    try {
      res = response.getOutputStream();
      // 清空输出流(在迅雷下载不会出现一长窜)
      response.reset();
      // 设定输出文件头
      response.setHeader("Content-Disposition", "attachment;fileName="
          + filename);
      response.setContentType("application/zip");
      zos = new ZipOutputStream(res);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  // 后处理
  public void afterProcess() {
    try {
      if (zos != null) {
        zos.close();
      }
      if (res != null) {
        res.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

3. 在struts.xml中配置

1
2
3
4
5
6
<action name="downLoadBkPersonLessionsZip" class="bkPersonLessionAction" 
      method="downLoadLessionsZip">//class值为bean.xml中配置的bean
  <result name="nodata" type="httpheader">
    <param name="status">204</param>//表示响应执行成功,但没有数据返回,浏览器不用刷新,不用导向新页面
  </result>
</action>

用到的jar包

DEMO下载地址:https://dwz.cn/Jw3z6fVq

Java实现批量下载选中文件功能的更多相关文章

  1. Java读取并下载网络文件

      CreateTime--2017年8月21日10:11:07 Author:Marydon import java.io.ByteArrayOutputStream; import java.io ...

  2. Python3 根据m3u8下载视频,批量下载ts文件并且合并

    Python3 根据m3u8下载视频,批量下载ts文件并且合并 m3u8是苹果公司推出一种视频播放标准,是一种文件检索格式,将视频切割成一小段一小段的ts格式的视频文件,然后存在服务器中(现在为了减少 ...

  3. java实现批量修改指定文件夹下所有后缀名的文件为另外后缀名的代码

    java实现批量修改指定文件夹下所有后缀名的文件为另外后缀名的代码 作者:Vashon package com.ywx.batchrename; import java.io.File; import ...

  4. Aras Innovator客户端批量下载关联文件

    <button onclick="btnDownload();" id="downfilebtn">批量下载关联文件</button> ...

  5. java/resteasy批量下载存储在阿里云OSS上的文件,并打包压缩

    现在需要从oss上面批量下载文件并压缩打包,搜了很多相关博客,均是缺胳膊少腿,要么是和官网说法不一,要么就压缩包工具类不给出 官方API https://help.aliyun.com/documen ...

  6. java+web+批量下载文件

    JavaWeb 文件下载功能 文件下载的实质就是文件拷贝,将文件从服务器端拷贝到浏览器端,所以文件下载需要IO技术将服务器端的文件读取到,然后写到response缓冲区中,然后再下载到个人客户端. 1 ...

  7. java多线程批量下载文件

    多线程下载文件 平时开发中有时会用到文件下载,为了提高文件的下载速率,采用多线程下载能够达到事半功倍的效果: package test; /** * 文件下载类 * @author luweichen ...

  8. Java实现批量下载《神秘的程序员》漫画

    上周看了西乔的博客“西乔的九卦”.<神秘的程序员们>系列漫画感觉很喜欢,很搞笑.这些漫画经常出现在CSDN“程序员”杂志末页的,以前也看过一些. 后来就想下载下来,但是一张一张的点击右键“ ...

  9. 【数据下载】利用wget命令批量下载ftp文件和文件夹

    这是一个“”数据大发现”的时代,大家都在创造数据,使用数据以及分享数据,首先一步我们就需要从数据库download我们需要的数据. Ftp是一种常见的在线数据库,今天介绍一种可以批量下载文件夹的方法, ...

随机推荐

  1. K nearest neighbor cs229

    vectorized code 带来的好处. import numpy as np from sklearn.datasets import fetch_mldata import time impo ...

  2. 异步消息处理机制相关面试问题-intentservice面试问题详解

    IntentService是什么? IntentService是继承并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService方法和启动传统的S ...

  3. python 获取安装包apk, ipa 信息

    # -*- coding:utf-8 -*- import re import os import zipfile from biplist import * from androguard.core ...

  4. C#学习之Timothy Liu

    原文出自 本文摘录了一些值得学习的地方. 1.对一个程序来说,静态指编辑期.编译期,动态指运行期. 静态时装在硬盘里,动态时装在内存里. 2.反射示例 通过反射获得类的属性和方法. static vo ...

  5. 点击startup.bat启动tomcat出现乱码

    找到tomcat目录下的/conf/logging.properties添加语句:java.util.logging.ConsoleHandler.encoding = GBK重启tomcat 问题解 ...

  6. Eclipse里Maven配置

    简单记录一下,太特么困了,这几天天天加班很晚来着 : 选中.Apply and Close. 完成. 日他得,腰都快加断了……:) ---------------------------------- ...

  7. Linux根目录下各目录文件类型及各项缩写全称

    bin(binary) :常见linux命令.系统所有用户命令目录文件dev(device) : 设备驱动存储目录文件media: 多媒体及挂载目录proc (process):进程信息文件sbin( ...

  8. Java-WEB开发常用方法整理

    /** * 此类中收集Java编程中WEB开发常用到的一些工具. * 为避免生成此类的实例,构造方法被申明为private类型的. * @author */ import java.io.IOExce ...

  9. 让create-react-app支持sass,less

    用create-react-app 创建的项目不支持sass和less,需要手动配置 npm install node-sass sass-loader --save 然后在config/webpac ...

  10. Monkey使用详情

    https://blog.csdn.net/zhangmeng1314/article/details/82699316 比如使用 adb shell input keyevent <keyco ...