Java實現zip壓縮多個文件下載

爲了更好的演示,首先建立一個文件實體FileBean,包含了文件路徑和文件名稱:java

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輸出到瀏覽器的客戶端:node

    /**
     * 打包壓縮下載文件
     */
    @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壓縮文件的工具類,這樣便實現了多文件的壓縮下載功能:web

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 下載普通單個文件的方法:spring

    @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[]> 實現下載單個文件的方法shell

    /**
     * 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>
相關文章
相關標籤/搜索