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

爲了更好的演示,首先創建一個文件實體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>
複製代碼
發佈了96 篇原創文章 · 獲贊 218 · 訪問量 64萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章