为了更好的演示,首先创建一个文件实体FileBean,包含了文件路径和文件名称:

package com.javaweb.entity;

import java.io.Serializable;
/**
* 文件实体类*/
public class FileBean implements Serializable{ private static final long serialVersionUID = -5452801884470115159L; private Integer fileId;//主键 private String filePath;//文件保存路径 private String fileName;//文件保存名称 public FileBean(){ } //Setters and Getters ...
}

接下来,在控制层的方法里(示例为Spring MVC),进行读入多个文件List<FileBean>,压缩成myfile.zip输出到浏览器的客户端:

    /**
* 打包压缩下载文件
*/
@RequestMapping(value = "/downLoadZipFile")
public void downLoadZipFile(HttpServletResponse response) throws IOException{
String zipName = "myfile.zip";
List<FileBean> fileList = fileService.getFileList();//查询数据库中记录
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename="+zipName);
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
try {
for(Iterator<FileBean> it = fileList.iterator();it.hasNext();){
FileBean file = it.next();
ZipUtils.doCompress(file.getFilePath()+file.getFileName(), out);
response.flushBuffer();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
}
}

最后,附上ZipUtils压缩文件的工具类,这样便实现了多文件的压缩下载功能:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; public class ZipUtils { private ZipUtils(){
} public static void doCompress(String srcFile, String zipFile) throws IOException {
doCompress(new File(srcFile), new File(zipFile));
} /**
* 文件压缩
* @param srcFile 目录或者单个文件
* @param zipFile 压缩后的ZIP文件
*/
public static void doCompress(File srcFile, File zipFile) throws IOException {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(zipFile));
doCompress(srcFile, out);
} catch (Exception e) {
throw e;
} finally {
out.close();//记得关闭资源
}
} public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
doCompress(new File(filelName), out);
} public static void doCompress(File file, ZipOutputStream out) throws IOException{
doCompress(file, out, "");
} public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
if ( inFile.isDirectory() ) {
File[] files = inFile.listFiles();
if (files!=null && files.length>0) {
for (File file : files) {
String name = inFile.getName();
if (!"".equals(dir)) {
name = dir + "/" + name;
}
ZipUtils.doCompress(file, out, name);
}
}
} else {
ZipUtils.doZip(inFile, out, dir);
}
} public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
String entryName = null;
if (!"".equals(dir)) {
entryName = dir + "/" + inFile.getName();
} else {
entryName = inFile.getName();
}
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry); int len = 0 ;
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(inFile);
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
out.closeEntry();
fis.close();
} public static void main(String[] args) throws IOException {
doCompress("D:/java/", "D:/java.zip");
} }

其他:spring mvc 下载普通单个文件的方法:

    @RequestMapping(value = "/downloadFile")
@ResponseBody
public void downloadFile (HttpServletResponse response) {
OutputStream os = null;
try {
       os = response.getOutputStream();
       File file = new File("D:/javaweb/demo.txt");
       // Spring工具获取项目resources里的文件
       File file2 = ResourceUtils.getFile("classpath:shell/init.sh");
if(!file.exists()){
          return;
       }
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=demo.txt");
response.setContentType("application/octet-stream; charset=utf-8");
os.write(FileUtils.readFileToByteArray(file));
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(os);
} }

补充,另外一种 利用 ResponseEntity<byte[]> 实现下载单个文件的方法:

    /**
* Spring下载文件
* @param request
* @throws IOException
*/
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{
     // 获取项目webapp目录路径下的文件
String path = request.getSession().getServletContext().getRealPath("/");
File file = new File(path+"/soft/javaweb.txt");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "javaweb.txt");
return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
  
<a target="_blank" href="/download">点击下载</a>

Java实现zip压缩多个文件下载的更多相关文章

  1. Java 的zip压缩和解压缩

    Java 的zip压缩和解压缩 好久没有来这写东西了,今天中秋节,有个东西想拿出来分享,一来是工作中遇到的问题,一来是和csdn问候一下,下面就分享一个Java中的zip压缩技术,代码实现比较简单,代 ...

  2. 用java实现zip压缩

    本来是写到spaces live上的,可是代码的显示效果确实不怎么好看.在javaeye上试了试代码显示的顺眼多了. 今天写了个用java压缩的功能,可以实现对文件和目录的压缩. 由于java.uti ...

  3. Java操作zip压缩和解压缩文件工具类

    需要用到ant.jar(这里使用的是ant-1.6.5.jar) import java.io.File; import java.io.FileInputStream; import java.io ...

  4. java.util.zip压缩打包文件总结二: ZIP解压技术

    一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: Checked ...

  5. java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹

    一.简述 zip用于压缩和解压文件.使用到的类有:ZipEntry  ZipOutputStream 二.具体实现代码 package com.joyplus.test; import java.io ...

  6. java基础---->Zip压缩的使用(转)

    java中提供了对压缩格式的数据流的读写.它们封装到现成的IO 类中,以提供压缩功能.下面我们开始java中压缩文件的使用. 目录导航: 关于压缩的简要说明 GZIP压缩文件的使用 ZIP压缩文件的使 ...

  7. java基础---->Zip压缩的使用

    java中提供了对压缩格式的数据流的读写.它们封装到现成的IO 类中,以提供压缩功能.下面我们开始java中压缩文件的使用. 目录导航: 关于压缩的简要说明 GZIP压缩文件的使用 ZIP压缩文件的使 ...

  8. JAVA实现zip压缩需要注意的问题

    近来对院社二维码平台进行2.0升级改造.于昨日踩到一个巨坑.特此记录... 需求源于院社编辑在批量下载二维码的时候,系统后台需要对所要下载的二维码进行重命名和zip打包压缩. 系统测试的时候发现:首次 ...

  9. java实现zip压缩和解压工具

    引入ant.jar package com.develop.web.util; import java.io.BufferedInputStream; import java.io.File; imp ...

随机推荐

  1. BZOJ4423 [AMPPZ2013]Bytehattan

    本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...

  2. 关于captive portal

    portal是入口的意思,我的理解,在这里其实就是门户或者主页.captive portal,就是强制主页.校园网里面的验证通常都是通过一个网页验证来完成,不管你点要访问哪一个网站,它都会强制给你转到 ...

  3. Sender

    多个对象用同一个方法的时候,想对多个对象分别操作的话就用Sender.  BackGroundWorker worker1 = sender as BackGroundWork.  分别去取当前的对象 ...

  4. hihocoder #1327

    传送门 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定一个只包含小写字母'a'-'z'的字符串 S ,你需要将 S 中的字符重新排序,使得任意两个相同的字符不连在一 ...

  5. String 与StringBuffer的区别与使用

    摘自:http://www.cnblogs.com/kaituorensheng/p/3776484.html 区别: String类是字符串常量,是不可更改的常量.而StringBuffer是字符串 ...

  6. Beta版本冲刺第二天 12.6

    一.站立式会议照片: 二.项目燃尽图: 三.项目进展: 成 员 昨天完成任务 今天完成任务 第三天冲刺要做任务 问题困难 心得体会 胡泽善 完成了"记住密码"的的逻辑以及BUG修改 ...

  7. Linux爆新漏洞,长按回车键70秒即可获得root权限

    漏洞来源这个安全问题来源于Cryptsetup存在的一个漏洞(CVE-2016-4484).Cryptsetup是在Linux统一密钥设置(Linux Unified Key Setup, LUKS) ...

  8. 《JavaScript权威指南》学习笔记 第六天 开始学习DOM了。

    昨天学习了window对象的一些方法.window对象主要是针对当前视窗的操作.window对象提供了一些列API来帮助我们了解当前窗口的信息.例如history对象可以让我们获取浏览历史.nvaig ...

  9. tomcat密码的坑

    <role rolename="tomcat"/> <role rolename="role1"/> <user username ...

  10. angular ui-router 缓存问题

    在个别情况下 $state.go()路径和参数完全相同的时候页面因为缓存问题可以直接跳转,但是不能重新获取数据 通过路由参数可以解决 路由 .state('app.***.***', { url: ' ...