controller层:

  1. /**
  2. * 打包压缩下载文件
  3. */
  4. @RequestMapping(value = "/downLoadZipFile")
  5. public void downLoadZipFile(HttpServletResponse response) throws IOException{
  6. String zipName = "myfile.zip";
  7. List<FileBean> fileList = fileService.getFileList();//查询数据库中记录
  8. response.setContentType("APPLICATION/OCTET-STREAM");
  9. response.setHeader("Content-Disposition","attachment; filename="+zipName);
  10. ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
  11. try {
  12. for(Iterator<FileBean> it = fileList.iterator();it.hasNext();){
  13. FileBean file = it.next();
  14. ZipUtils.doCompress(file.getFilePath()+file.getFileName(), out);
  15. response.flushBuffer();
  16. }
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }finally{
  20. out.close();
  21. }
  22. }

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

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

压缩工具类:

  1. package com.m2plat.puhui.utils;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5.  
  6. import java.io.*;
  7. import java.util.zip.ZipEntry;
  8. import java.util.zip.ZipOutputStream;
  9.  
  10. /**
  11. * 文件压缩工具类
  12. * Created by xiangzh on 2018/11/20.
  13. */
  14. public class ZipUtils {
  15.  
  16. private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);
  17.  
  18. private ZipUtils(){
  19. }
  20.  
  21. public static void doCompress(String srcFile, String zipFile) throws IOException {
  22. doCompress(new File(srcFile), new File(zipFile));
  23. }
  24.  
  25. /**
  26. * 文件压缩
  27. * @param srcFile 目录或者单个文件
  28. * @param zipFile 压缩后的ZIP文件
  29. */
  30. public static void doCompress(File srcFile, File zipFile) throws IOException {
  31. ZipOutputStream out = null;
  32. try {
  33. out = new ZipOutputStream(new FileOutputStream(zipFile));
  34. doCompress(srcFile, out);
  35. } catch (Exception e) {
  36. throw e;
  37. } finally {
  38. out.close();//记得关闭资源
  39. }
  40. }
  41.  
  42. public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
  43. doCompress(new File(filelName), out);
  44. }
  45.  
  46. public static void doCompress(File file, ZipOutputStream out) throws IOException{
  47. doCompress(file, out, "");
  48. }
  49.  
  50. public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
  51. if ( inFile.isDirectory() ) {
  52. File[] files = inFile.listFiles();
  53. if (files!=null && files.length>0) {
  54. for (File file : files) {
  55. String name = inFile.getName();
  56. if (!"".equals(dir)) {
  57. name = dir + "/" + name;
  58. }
  59. ZipUtils.doCompress(file, out, name);
  60. }
  61. }
  62. } else {
  63. ZipUtils.doZip(inFile, out, dir);
  64. }
  65. }
  66.  
  67. public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
  68. String entryName = null;
  69. if (!"".equals(dir)) {
  70. entryName = dir + "/" + inFile.getName();
  71. } else {
  72. entryName = inFile.getName();
  73. }
  74. ZipEntry entry = new ZipEntry(entryName);
  75. out.putNextEntry(entry);
  76.  
  77. int len = 0 ;
  78. byte[] buffer = new byte[1024];
  79. FileInputStream fis = new FileInputStream(inFile);
  80. while ((len = fis.read(buffer)) > 0) {
  81. out.write(buffer, 0, len);
  82. out.flush();
  83. }
  84. out.closeEntry();
  85. fis.close();
  86. }
  87.  
  88. public static void doZip(InputStream in ,ZipOutputStream out, String entryName) throws IOException {
  89. logger.info("---添加InputStream到压缩文件,InputStream大小:{}",in.available());
  90. ZipEntry entry = new ZipEntry(entryName);
  91. out.putNextEntry(entry);
  92. int len = 0 ;
  93. byte[] buffer = new byte[1024*5];
  94. while ((len = in.read(buffer)) > 0) {
  95. out.write(buffer, 0, len);
  96. out.flush();
  97. }
  98. out.closeEntry();
  99. in.close();
  100. }
  101.  
  102. public static void main(String[] args) throws IOException {
  103. doCompress("D:/excel/puhui/1", "D:/附件.zip");
  104. }
  105.  
  106. }

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

  1. @RequestMapping(value = "/downloadFile")
  2. @ResponseBody
  3. public void downloadFile (HttpServletResponse response) {
  4. OutputStream os = null;
  5. try {
  6.        os = response.getOutputStream();
  7.        File file = new File("D:/javaweb/demo.txt");
  8.        // Spring工具获取项目resources里的文件
  9.        File file2 = ResourceUtils.getFile("classpath:shell/init.sh");
  10. if(!file.exists()){
  11.           return;
  12.        }
  13. response.reset();
  14. response.setHeader("Content-Disposition", "attachment;filename=demo.txt");
  15. response.setContentType("application/octet-stream; charset=utf-8");
  16. os.write(FileUtils.readFileToByteArray(file));
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }finally{
  20. IOUtils.closeQuietly(os);
  21. }
  22.  
  23. }

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

  1. /**
  2. * Spring下载文件
  3. * @param request
  4. * @throws IOException
  5. */
  6. @RequestMapping(value="/download")
  7. public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{
  8.      // 获取项目webapp目录路径下的文件
  9. String path = request.getSession().getServletContext().getRealPath("/");
  10. File file = new File(path+"/soft/javaweb.txt");
  11. HttpHeaders headers = new HttpHeaders();
  12. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  13. headers.setContentDispositionFormData("attachment", "javaweb.txt");
  14. return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
  15. }
  16.   
  17. <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. Makefile--基本规则(零)

    [版权声明:转载请保留出处:周学伟:http://www.cnblogs.com/zxouxuewei/] 一般一个稍大的linux项目会有很多个源文件组成,最终的可执行程序也是由这许多个源文件编译链 ...

  2. Mysql综合案例

    Mysql综合案例 考核要点:创建数据表.单表查询.多表查询 已知,有一个学生表student和一个分数表score,请按要求对这两个表进行操作.student表和score分数表的表结构分别如表1- ...

  3. java中被遗忘的native关键字

    我是无意间看见JNI( java调用动态链接库dll )这块的东西. 所有记下来:本地声明方法  装载完成dll文件后,将使用的方法用native关键字声明. public native static ...

  4. docker学习-docker容器

  5. idea & datagrip 注册码

    CNEKJPQZEX-eyJsaWNlbnNlSWQiOiJDTkVLSlBRWkVYIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiI ...

  6. UITextView和UITextField的placeholder,键盘隐藏,键盘换行变完成字样

    本文转载至 http://blog.csdn.net/hengshujiyi/article/details/9086093- (void)initFeedBackViews { //设置页面的背景颜 ...

  7. Mybatis之typeAlias配置的3种方法

    1.定义别名: <typeAliases> <typeAlias alias="User" type="cn.lxc.vo.User" /&g ...

  8. js将字符串转换为数字等类型

    1.js提供了parseInt()和parseFloat()两个转换函数. 2.ECMAScript中可用的3种强制类型转换如下:  Boolean(value)——把给定的值转换成Boolean型: ...

  9. iOS - 布局重绘机制相关方法的研究

    iOS View布局重绘机制相关方法 布局 - (void)layoutSubviews - (void)layoutIfNeeded- (void)setNeedsLayout —————————— ...

  10. mac下搭建cocos2d-x2.2.1版本android编译环境教程

    首先我们先以引擎2.2.1为例子来新建一个TestJni的项目,来作为测试例. 创建方式如下: python create_project.py -project TestJni -package o ...