分享

Java实现zip压缩多个文件下载

 青_春 2017-07-11

为了更好的演示,首先创建一个文件实体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(List<FileBean> fileList, HttpServletResponse response) throws IOException{
        String zipName = "myfile.zip";
        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.zipFile(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 { public static void doCompress(String srcFile, String zipFile) throws Exception { doCompress(new File(srcFile), new File(zipFile)); } /** * 文件压缩 * @param srcFile 目录或者单个文件 * @param destFile 压缩后的ZIP文件 */ public static void doCompress(File srcFile, File destFile) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile)); if(srcFile.isDirectory()){ File[] files = srcFile.listFiles(); for(File file : files){ doCompress(file, out); } }else { doCompress(srcFile, out); } } public static void doCompress(String pathname, ZipOutputStream out) throws IOException{ doCompress(new File(pathname), out); } public static void doCompress(File file, ZipOutputStream out) throws IOException{ if( file.exists() ){ byte[] buffer = new byte[1024]; FileInputStream fis = new FileInputStream(file); out.putNextEntry(new ZipEntry(file.getName())); int len = 0 ; // 读取文件的内容,打包到zip文件 while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); out.closeEntry(); fis.close(); } } }
复制代码

 

普通单个文件的下载方法:

复制代码
    @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/sinit.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.zip"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", "javaweb.zip"); return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED); }
  
<a target="_blank" href="/download">点击下载</a>
复制代码

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多