为了更好的演示,首先创建一个文件实体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. text-indent无效解决方案

    text-indent是用来字符缩进的. 1.text-indent所在的元素是行内元素而非块级元素.比如用在span,a等行内元素上.解决方案:在行内元素加上display:block; 或者把目标 ...

  2. ModSecurity web application firewall (WAF) Research

    catalog . 引言 . OWASP ModSecurity Core Rule Set (CRS) Project . Installation mod_security for Apache ...

  3. POJ 2492 A Bug's Life

    传送门:A Bug's Life Description Background Professor Hopper is researching the sexual behavior of a rar ...

  4. Linux命令点滴积累

    1.批量删除当前目录及子目录中指定类型的文件: [root@localhost logs]# find ./ -name *.bak | xargs rm -rf [root@localhost lo ...

  5. [Android]Volley源码分析(一)

    一. 如何使用Volley? 1. 首先定义一个RequestManager类,用来在Android程序启动时对Volley进行初始化.RequestManager为单例类,因为只有在程序启动时调用, ...

  6. Code笔记之:CSS块级元素、内联元素概念

    文档流 将窗体自上而下分成一行行, 并在每行中按从左至右的顺序排放元素,即为文档流. 每个非浮动块级元素都独占一行, 浮动元素则按规定浮在行的一端. 若当前行容不下, 则另起新行再浮动. 内联元素也不 ...

  7. jQuery焦点不在输入框内判断不能为空

    我能说JS和jquery有时候都有病吗?同样的代码,重敲一遍可以了,再过一会不行了.再试一下重敲,一模一样的代码,也不报错.就是不行.反复折腾.... 我帖上来的是经过了1个小时同等功能的测试OK的, ...

  8. OpenGLES入门笔记二

    #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> #import <OpenGLES/ES2/gl.h& ...

  9. Hook技术

    hook钩子: 使用技术手段在运行时动态的将额外代码依附现进程,从而实现替换现有处理逻辑或插入额外功能的目的. 它的技术实现要点有两个: 1)如何注入代码(如何将额外代码依附于现有代码中). 2)如何 ...

  10. CentOS编译安装NodeJS+Express

    NodeJS是基于Chrome’s Javascript runtime,也就是Google V8引擎执行Javascript的快速构建网络服务及应用的平台,其优点有: 在CentOS编译安装Node ...