萬盛學電腦網

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

JSP 多檔案打包下載:ZIP 串流輸出完整實作

功能需求

使用者在前端勾選多個檔案,後端將其壓縮為單一 ZIP 檔案,以串流方式直接輸出下載,不佔用伺服器磁碟暫存空間。

核心實作代碼

<%@ page import="java.util.*, java.net.*, java.text.*, java.util.zip.*, java.io.*" %>
<%!
    // 遞歸展開檔案列表(含子目錄)
    static Vector expandFileList(String[] files, boolean inclDirs) {
        Vector v = new Vector();
        if (files == null) return v;
        for (int j = 0; j < files.length; j++) {
            v.add(new File(URLDecoder.decode(files[j])));
        }
        for (int i = 0; i < v.size(); i++) {
            File f = (File) v.get(i);
            if (f.isDirectory()) {
                File[] fs = f.listFiles();
                for (int n = 0; n < fs.length; n++) v.add(fs[n]);
                if (!inclDirs) { v.remove(i); i--; }
            }
        }
        return v;
    }

    // 將 ZipOutputStream 寫入 JSP out 隱含物件
    class Writer2Stream extends OutputStream {
        Writer out;
        Writer2Stream(Writer w) { super(); out = w; }
        public void write(int i) throws IOException { out.write(i); }
        public void write(byte[] b) throws IOException {
            for (int j = 0; j < b.length; j++) {
                int n = b[j]; n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
                out.write(n);
            }
        }
        public void write(byte[] b, int off, int len) throws IOException {
            for (int j = off; j < off + len; j++) {
                int n = b[j]; n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
                out.write(n);
            }
        }
    }
%>
<%
    // 接收前端勾選的檔案參數 (name="selfile")
    Vector v = expandFileList(request.getParameterValues("selfile"), false);
    if (v.size() == 0) {
        request.setAttribute("error", "No files selected");
    } else {
        File dir_file = new File(request.getRealPath("") + "/myfile/");
        int dir_l = dir_file.getAbsolutePath().length();

        // 設定響應標頭:ZIP 下載
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=downloadname.zip");
        out.clearBuffer();

        // 核心:直接串流壓縮輸出
        ZipOutputStream zipout = new ZipOutputStream(new Writer2Stream(out));
        zipout.setComment("Download selected files as one ZIP file: downloadname.zip");
        zipout.setLevel(1); // 壓縮等級 1 (最快)

        for (int i = 0; i < v.size(); i++) {
            File f = (File) v.get(i);
            if (f.canRead()) {
                // ZIP 內相對路徑
                zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1)));
                BufferedInputStream fr = new BufferedInputStream(new FileInputStream(f));
                byte[] buffer = new byte[0xffff];
                int b;
                while ((b = fr.read()) != -1) zipout.write(b);
                fr.close();
                zipout.closeEntry();
            }
        }
        zipout.finish();
        out.flush();
    }
%>

關鍵技術點解析

  1. Writer2Stream 適配器:將 ZipOutputStream (位元組流) 寫入 JSP out (字元流),解決二進位資料直接輸出的編碼問題。
  2. 串流式壓縮:邊讀檔案邊寫入 ZIP 串流,無需建立臨時 ZIP 檔案,記憶體佔用極低。
  3. 遞歸展開目錄:expandFileList 支援資料夾遞歸,inclDirs=false 表示不將目錄本身加入壓縮包。
  4. Content-Disposition:attachment;filename=xxx.zip 強制瀏覽器彈出下載對話框。

前端表單範例

<form action="download.zip.jsp" method="post">
    <input type="checkbox" name="selfile" value="/myfile/doc1.pdf"> 文件1.pdf<br>
    <input type="checkbox" name="selfile" value="/myfile/image.jpg"> 圖片.jpg<br>
    <input type="checkbox" name="selfile" value="/myfile/folder/"> 整個資料夾<br>
    <input type="submit" value="打包下載">
</form>

注意事項與優化

  • 大檔案建議使用 ZipOutputStream.putNextEntry 後分塊 read(buf) 寫入,避免單次 read() 效率過低。
  • 生產環境應加入檔案大小限制、下載流量控制、權限檢查。
  • 若需支援中文檔名,請使用 ZipEntry 建構子指定 UTF-8 編碼 (Java 7+):new ZipEntry(name, StandardCharsets.UTF_8)。
  • JSP 輸出二進位資料前務必 out.clearBuffer(),並避免頁面有任何空白字元輸出。
copyright © 萬盛學電腦網 all rights reserved