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文件的压缩包 (二 ...
随机推荐
- url传参错误的痛
今天用一下方法给后台传参数: var url = 'patrolpoint!totalHistoryPage.action' + '?patrolPoint.batchOnTime=' ...
- Unity3D Android手机屏幕分辨率问题
Android手机屏幕分辨率五花八门,导致开发时不好把握,还好各个引擎对这个屏幕分辨率问题都有较好的处理方式:unity3D 也为我们提供了一个不错的解决方案. 在Unity3D 进行 android ...
- JavaScript------字符串与HTML格式相互转换
转载: http://blog.sina.com.cn/s/blog_4cb0b0fc0100aoo1.html 代码:: 1.将字符转换成Html function encodeHtml(str){ ...
- mybatis由浅入深day01_1课程安排_2对原生态jdbc程序中问题总结
mybatis 第一天 mybatis的基础知识 1 课程安排: mybatis和springmvc通过订单商品 案例驱动 第一天:基础知识(重点,内容量多) 对原生态jdbc程序(单独使用jdbc开 ...
- ionic安装及测试
官方教程: http://ionicframework.com/getting-started/ 官方教程写得比较简单,简单来说就是 1)安装nodejs(安装方法:http://www.cnblog ...
- Linux 任务计划:crontab
(1) 什么是任务计划:也就是设置服务器在某个指定的时间执行某个指定的任务,比如执行一个命令,或执行一个脚本(2) Linux 使用 cron 服务来制定任务计划,cron 是服务名称,crond 是 ...
- IIS7以上版本去掉伪静态去掉index.php方法
1,由于从iis7以上的版本httpd.ini文件已不会被解析,将以下的xml文件复制到web.config 的文件中,然后放到网站的根目录即可. <?xml version="1.0 ...
- 96、facebook Fresco框架库源使用(转载)
各个属性详情:http://blog.csdn.net/y1scp/article/details/49245535 开源项目链接 facebook Fresco仓库:git clone https: ...
- [分享]方便的 windbg 命令 - !list
Windows 内部的各种结构通常都会由双向链表串起来,用 !list 命令查看这些结构非常方便. 比如查看系统中的所有进程: lkd> !list -t nt!_LIST_ENTRY.Flin ...
- django restframwork教程之Request和Response
从这一篇文章开始,我们会覆盖整个REST framwork框架的核心,接下来让我们介绍一些基础的构建块 Request 对象 REST framework 引入了一个扩展HttpRequest的请求对 ...