萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 實現目錄壓縮為 ZIP 檔案的完整原始碼

功能描述

在 JSP 頁面中呼叫 Java 方法,將指定目錄遞歸壓縮為 ZIP 檔案,支援 Linux/Windows,處理編碼與大檔案流式寫入。

核心程式碼

<%@ page import="java.io.*, java.util.zip.*, javax.servlet.jsp.JspWriter" %>
<%
  // 壓縮入口方法
  public void zip(String zipPath, String srcPath, JspWriter out) throws Exception {
    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    try {
      fos = new FileOutputStream(zipPath);
      zos = new ZipOutputStream(new BufferedOutputStream(fos));
      zipEntry(zos, srcPath, srcPath, zipPath);
      out.print("ZIP 壓縮成功:" + zipPath);
    } catch (Exception e) {
      out.print("壓縮失敗:" + e.getMessage());
      e.printStackTrace();
    } finally {
      if (zos != null) try { zos.close(); } catch (IOException ignored) {}
    }
  }

  // 遞歸添加 ZIP 條目
  public void zipEntry(ZipOutputStream zos, String basePath, String filePath, String zipPath) throws Exception {
    File file = new File(filePath);
    if (file.isDirectory()) {
      String[] children = file.list();
      if (children != null) {
        for (String child : children) {
          zipEntry(zos, basePath, filePath + File.separator + child, zipPath);
        }
      }
      return;
    }

    // 計算 ZIP 內部相對路徑(去除基礎路徑前綴)
    String entryName = filePath.substring(basePath.length() + 1);
    // 統一使用正斜線,相容跨平台解壓
    entryName = entryName.replace(File.separatorChar, '/');

    // 避免將輸出的 ZIP 檔自己也壓縮進去
    if (file.getAbsolutePath().equals(new File(zipPath).getAbsolutePath())) return;

    ZipEntry entry = new ZipEntry(entryName);
    entry.setSize(file.length());
    entry.setTime(file.lastModified());
    zos.putNextEntry(entry);

    // 流式讀寫,避免大檔案 OOM
    try (FileInputStream fis = new FileInputStream(file);
         BufferedInputStream bis = new BufferedInputStream(fis)) {
      byte[] buffer = new byte[8192];
      int len;
      while ((len = bis.read(buffer)) != -1) {
        zos.write(buffer, 0, len);
      }
    }
    zos.closeEntry();
  }
%>

JSP 調用範例

<%
  String srcDir = application.getRealPath("/WEB-INF/export/data");
  String zipFile = application.getRealPath("/WEB-INF/export/data_backup.zip");
  zip(zipFile, srcDir, out);
%>

關鍵技術點解析

技術點處理方式
編碼問題ZIP 標準不指定編碼,建議檔名僅用 ASCII;若需中文檔名,需使用 Zip4j 或 Apache Commons Compress 指定 UTF-8 編碼。
大檔案支援使用 8KB 緩衝區流式讀寫,不將整個檔案載入記憶體。
空目錄處理遞歸時 file.list() 回傳 null 需防呆。
路徑分隔符統一轉為 /,確保跨平台解壓一致性。
排除輸出檔比對絕對路徑避免自我壓縮導致無限遞歸。

現代化建議:使用成熟庫

<!-- Maven 依賴 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-compress</artifactId>
  <version>1.26.0</version>
</dependency>
// 使用 Commons Compress(支援 UTF-8 檔名、大檔案、多執行緒)
try (ArchiveOutputStream out = new ArchiveStreamFactory()
        .createArchiveOutputStream("zip", new FileOutputStream(zipFile))) {
  out.putArchiveEntry(new ZipArchiveEntry(entryName));
  Files.copy(file.toPath(), out);
  out.closeArchiveEntry();
}

安全性提醒

  • JSP 執行任意檔案壓縮屬高風險操作,嚴禁直接暴露給前端呼叫。
  • 必須驗證路徑參數,防止路徑遍歷攻擊(../../etc/passwd)。
  • 生產環境建議移至後端 Service/Controller,透過 AJAX 觸發非同步任務,前端輪詢進度。
copyright © 萬盛學電腦網 all rights reserved