Java压缩多个文件并导出
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压缩多个文件并导出的更多相关文章
- 【转】Java压缩和解压文件工具类ZipUtil
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- JAVA实用案例之文件导入导出(POI方式)
1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...
- java压缩多个文件
首先创建一个工具类,定义好接口,这里的参数1:fileList:多个文件的path+name2: zipFileName:压缩后的文件名 下面是代码,注释已经很详细了 public class ZIP ...
- JAVA实用案例之文件导出(JasperReport踩坑实录)
写在最前面 想想来新公司也快五个月了,恍惚一瞬间. 翻了翻博客,因为太忙,也有将近五个多月没认真总结过了. 正好趁着今天老婆出门团建的机会,记录下最近这段时间遇到的大坑-JasperReport. 六 ...
- java如何压缩多个文件到压缩包,并下载到浏览器?
java压缩多个文件到压缩包,并下载到浏览器 解决方法: 完整的方法如下,很简单,亲试有效,极力推荐. 我是以流作为文件,而不是file,循环把所有pdf文件压缩到pdf.zip压缩包中. 1.前 ...
- Java Itext 生成PDF文件
利用Java Itext生成PDF文件并导出,实现效果如下: PDFUtil.java package com.jeeplus.modules.order.util; import java.io.O ...
- java压缩文件或文件夹并导出
java压缩文件或文件夹并导出 tozipUtil: package com.zhl.push.Utils; import java.io.File; import java.io.FileInput ...
- java实现多个文件以压缩包导出到本地
描述:使用java将多个文件同时压缩为压缩包,并导出到本地 /** *压缩文件并导出 */ public static void zipFiles() throws IOException { Fil ...
- JAVA核心技术I---JAVA基础知识(Jar文件导入导出)
一:Jar初识 (一)定义 同c++中的DLL一样 jar文件,一种扩展名为jar的文件,是Java所特有的一种文件格式,用于可执行程序文件的传播. jar文件实际上是一组class文件的压缩包 (二 ...
随机推荐
- hadoop基础学习---基本概念
1.组成部分HDFS和MapReduce 2.HDFS这几架构
- RAC:Oracle11gR2:群集的起、停、状态查询
一:查看群集的状态 1.0.1 使用crsctl status resource [-t] 1.0.2 使用crs_stat [-t] 1.0.1 使用srvctl status <obj> ...
- 如何用MathType编辑集合运算符号
在涉及到集合的运算中,有交并且几种常见的运算,这在数学问题中也是很常见的公式.在用MathType编辑这些符号时,该怎么编辑呢?下面就介绍MathType集合运算符号的编辑方法. 具体操作过程如下: ...
- catch(…) vs catch(CException *)?
转自:https://stackoverflow.com/questions/7412185/what-is-the-difference-between-catch-vs-catchcexcepti ...
- android素材资源
这里先给大家 推荐两个 找图标的 搜索引擎 http://findicons.com/ 这个我也在用 大家也可以试试 找个图标还是很easy的. http://www.iconfinder. ...
- Javascript 字符串替换
<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content=& ...
- python2.0_s12_day19_前端模版使用
Django中引用bootstrap实现在前端可以创建客户信息,可以修改客户信息我们需要设计一个前端用户交互系统.我们在设计之前,讨论一些需求:前端实现:1. 不同角色的用户,看到的东西是不一样的 销 ...
- python计算时间差的方法
本文实例讲述了python计算时间差的方法.分享给大家供大家参考.具体分析如下: 1.问题: 给定你两个日期,如何计算这两个日期之间间隔几天,几个星期,几个月,几年? 2.解决方法: 标准模块date ...
- oracle 与mysql 的当前时间比较
select p.id,p.order_Num,p.image_url,p.url,p.image_topic, p.is_download, p.big_image_url, p.begin_tim ...
- JAXB简单样例
参考网页:http://www.mkyong.com/java/jaxb-hello-world-example/JAXB完整教程:https://jaxb.java.net/tutorial/1.J ...