为了更好的演示,首先创建一个文件实体FileBean,包含了文件路径和文件名称:

package com.javaweb.entity;

import java.io.Serializable;
/**
* 文件实体类*/
public class FileBean implements Serializable{ private static final long serialVersionUID = -5452801884470115159L; private Integer fileId;//主键 private String filePath;//文件保存路径 private String fileName;//文件保存名称 public FileBean(){ } //Setters and Getters ...
}

接下来,在控制层的方法里(示例为Spring MVC),进行读入多个文件List<FileBean>,压缩成myfile.zip输出到浏览器的客户端:

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

最后,附上ZipUtils压缩文件的工具类,这样便实现了多文件的压缩下载功能:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; public class ZipUtils { 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 main(String[] args) throws IOException {
doCompress("D:/java/", "D:/java.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>

最新文章

  1. mac os 下打开FTP服务器
  2. C++ list的基本操作和使用
  3. Linux sed 替换第一次出现的字符串
  4. 剑指offer习题集1
  5. AreYouBusy
  6. 小白日记26:kali渗透测试之提权(六)--收集敏感信息,隐藏痕迹
  7. 第46条:for-each循环优先于传统的for循环
  8. 【线段树求逆序数】【HDU1394】Minimum Inversion Number
  9. java——String的那边破事
  10. (step5.1.3)hdu 1213( How Many Tables——1213)
  11. 如何使用Node.js编写命令工具——以vue-cli为例
  12. Day3 文件操作和函数
  13. 解决IE6-IE7下li上下间距变大问题
  14. Python 虚拟环境[virtualenv/virtualenvwrapper]设置
  15. java9 Local-variable type inference
  16. list 的 增 删
  17. Git Windows 安装
  18. happypack 进一步 优化 build速率
  19. CentOS下zabbix监控mysql5.6版本主从
  20. P3811 【模板】乘法逆元

热门文章

  1. 【bzoj1497】 NOI2006—最大获利
  2. karottc A Simple linux-virus Analysis、Linux Kernel &lt;= 2.6.37 - Local Privilege Escalation、CVE-2010-4258、CVE-2010-3849、CVE-2010-3850
  3. Handlers
  4. Nginx系列3之Nginx+tomcat
  5. (翻译)如何对python dict 类型按键(keys)或值(values)排序
  6. HTTPS背后的加密算法
  7. windows系统下安装MySQL
  8. css005 用层叠管理多样式
  9. winform 窗体传值
  10. asp.net与Matlab类型转换(待补全)