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. ubuntu-14.04.2-desktop-amd64.iso:ubuntu-14.04.2-desktop-amd64:安装Oracle11gR2

    ubuntu 桌面版的安装不介绍. 如何安装oracle:核心步骤和关键点. ln -sf /bin/bash /bin/sh ln -sf /usr/bin/basename /bin/basena ...

  2. Effective C++ Item 19 Treat class design as type design

    Too high class topic for me now ................... ................... ................... fill the ...

  3. centos无法联网解决方法

    1)进入 /etc/sysconfig/network-scripts/ 2)vi 或 vim 打开 ifcfg-eth0(不一定是eth0,这个自己判断了) 3)将 ONBOOT=no 改成 ONB ...

  4. 如何在单片机上使用printf函数(printf)(avr)(stm)(lpc)(单片机)(转)

    摘要:    当我们在调试代码时,通常需要将程序中的某个变量打印至PC机上,来判断我们的程序是否按预期的运行,printf函数很好的做到了这一点,它能直接以字符的方式输出变量名和变量的值,printf ...

  5. u盘装系统,u盘安装win7系统教程

    http://www.upanboot.com/tool/anzhuang_win7.html 可以用本教程给笔记本.台式机.上网本和组装电脑通过U盘安装Win7系统. 步骤一.首先要准备一个至少8G ...

  6. Delphi 有关的网址

    1.  博客园 (张志峰)    http://www.cnblogs.com/zhangzhifeng/ 2. CSDN  Delphi论坛        https://bbs.csdn.net/ ...

  7. Android Log.isLoggable方法异常:exceeds limit of 23 characters

    AndroidRuntime: java.lang.IllegalArgumentException: Log tag "AccountSetupIncomingFragment" ...

  8. C++ 初始化函数的实现

    http://www.cppblog.com/xlshcn/archive/2007/11/21/37088.aspx

  9. android 仿微信聊天界面,以及语音录制功能

    extends:http://104zz.iteye.com/blog/1709840 本例为模仿微信聊天界面UI设计,文字发送以及语言录制UI. 1先看效果图:     第一:chat.xml设计 ...

  10. Unity3D笔记三 物理引擎

    一.物理引擎 1.物理引擎就是模拟真实世界中物体碰撞.跌落等反应,通过Ballance.愤怒的小鸟来理解什么是物理引擎.Unity的物理引擎使用的是NviDIA的PhysX.2.选中一个游戏对象,主菜 ...