controller层:

/**
* 打包压缩下载文件
*/
@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();
}
}

如果需要支持跨域,在controller中添加代码:

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Method", "POST,GET");

压缩工具类:

package com.m2plat.puhui.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; /**
* 文件压缩工具类
* Created by xiangzh on 2018/11/20.
*/
public class ZipUtils { private static Logger logger = LoggerFactory.getLogger(ZipUtils.class); 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 doZip(InputStream in ,ZipOutputStream out, String entryName) throws IOException {
logger.info("---添加InputStream到压缩文件,InputStream大小:{}",in.available());
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
int len = 0 ;
byte[] buffer = new byte[1024*5];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
out.closeEntry();
in.close();
} public static void main(String[] args) throws IOException {
doCompress("D:/excel/puhui/1", "D:/附件.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压缩多个文件下载

Java压缩多个文件并导出的更多相关文章

  1. 【转】Java压缩和解压文件工具类ZipUtil

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  2. JAVA实用案例之文件导入导出(POI方式)

    1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...

  3. java压缩多个文件

    首先创建一个工具类,定义好接口,这里的参数1:fileList:多个文件的path+name2: zipFileName:压缩后的文件名 下面是代码,注释已经很详细了 public class ZIP ...

  4. JAVA实用案例之文件导出(JasperReport踩坑实录)

    写在最前面 想想来新公司也快五个月了,恍惚一瞬间. 翻了翻博客,因为太忙,也有将近五个多月没认真总结过了. 正好趁着今天老婆出门团建的机会,记录下最近这段时间遇到的大坑-JasperReport. 六 ...

  5. java如何压缩多个文件到压缩包,并下载到浏览器?

    java压缩多个文件到压缩包,并下载到浏览器   解决方法: 完整的方法如下,很简单,亲试有效,极力推荐. 我是以流作为文件,而不是file,循环把所有pdf文件压缩到pdf.zip压缩包中. 1.前 ...

  6. Java Itext 生成PDF文件

    利用Java Itext生成PDF文件并导出,实现效果如下: PDFUtil.java package com.jeeplus.modules.order.util; import java.io.O ...

  7. java压缩文件或文件夹并导出

    java压缩文件或文件夹并导出 tozipUtil: package com.zhl.push.Utils; import java.io.File; import java.io.FileInput ...

  8. java实现多个文件以压缩包导出到本地

    描述:使用java将多个文件同时压缩为压缩包,并导出到本地 /** *压缩文件并导出 */ public static void zipFiles() throws IOException { Fil ...

  9. JAVA核心技术I---JAVA基础知识(Jar文件导入导出)

    一:Jar初识 (一)定义 同c++中的DLL一样 jar文件,一种扩展名为jar的文件,是Java所特有的一种文件格式,用于可执行程序文件的传播. jar文件实际上是一组class文件的压缩包 (二 ...

随机推荐

  1. 解决myeclipse4.1.1对一个表生成映射文件的时候,出现“generating artifacts"的解决!

    很多人在用myeclipse4.1.1对一个表生成映射文件的时候,都出现“generating artifacts"的问题.我也遇到了这个问题,弄得我也很郁闷!看了很多人的帖子后还是无法搞定 ...

  2. 【R markdown】rmysql乱码问题

    统计数据遇到在Rmarkdown文档中通过rmysql查询中文结果乱码的现象. 数据库编码 utf8 rmd编码utf8 猜测是生成的html编码非utf8 解决方案是: dbSendQuery(co ...

  3. MathType公式波浪线怎么编辑

    数学公式中有很多符号与数学样式,在用手写时是没有问题的,但是很多论文或者期刊中也是需要用到这些符号或者样式的,比如公式波浪线,那么MathType公式波浪线怎么编辑出来呢? 具体操作步骤如下: 1.打 ...

  4. 帝国CMS当前位置中的“首页”二字如何修改

    1.帝国CMS当前位置首页那两个字在哪里可以修改吗? 2.[!--newsnav--]该处的首页链接,请问在哪儿修改? 3.导航条[!--newsnav--]默认首页为:“首页”可以更改么? 4.导航 ...

  5. zookeeper 系列文章

    http://blog.csdn.net/tswisdom/article/details/41522069 http://blog.csdn.net/tswisdom/article/details ...

  6. V4L2规范编程--21

    原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/ 资料链接:http://www.cnblogs.com/emouse/archive/2013/ ...

  7. [转]ASP.NET MVC 5 - 创建连接字符串(Connection String)并使用SQL Server LocalDB

    您创建的MovieDBContext类负责处理连接到数据库,并将Movie对象映射到数据库记录的任务中.你可能会问一个问题,如何指定它将连接到数据库? 实际上,确实没有指定要使用的数据库,Entity ...

  8. java编写的2048程序

    import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util ...

  9. 说说NAND FLASH以及相关ECC校验方法

    Flash名称的由来,Flash的擦除操作是以block块为单位的,与此相对应的是其他很多存储设备,是以bit位为最小读取/写入的单位,Flash是一次性地擦除整个块:在发送一个擦除命令后,一次性地将 ...

  10. jquery单选框radio绑定click事件实现和是否选中的方法

    使用jquery获取radio的值,最重要的是掌握jquery选择器的使用,在一个表单中我们通常是要获取被选中的那个radio项的值,所以要加checked来筛选,比如有以下的一些radio项: 1. ...