使用者在前端勾選多個檔案,後端將其壓縮為單一 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();
}
%>
ZipOutputStream (位元組流) 寫入 JSP out (字元流),解決二進位資料直接輸出的編碼問題。expandFileList 支援資料夾遞歸,inclDirs=false 表示不將目錄本身加入壓縮包。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)。out.clearBuffer(),並避免頁面有任何空白字元輸出。