private OutputStream res;
private ZipOutputStream zos;
// action的主方法
public String execute() throws Exception {
if (有數據可下載) {;
// 預處理
preProcess();
} else {
// 沒有文件可下載的場合,返回nodata,設定參照struts配置文件
return "nodata";
}
// 在這里編輯好需要下載的數據
風之境地 // 文件可以是硬盤上的
// 文件也可以是自己寫得數據流,如果是自己寫得數據流,請參看outputZipFile方法中的【2.】
File file = new File();
file = ...
outputZipFile(file);
// 后處理
afterProcess();
return null;
}
// 預處理
public void preProcess() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
res = response.getOutputStream();
//清空輸出流
response.reset();
//設定輸出文件頭
response.setHeader("Content-disposition ","attachment; filename=a.zip ");
response.setContentType("application/zip");
zos = new ZipOutputStream(res);
}
// 后處理
public void afterProcess() throws Exception {
zos.close();
res.close();
}
// 寫文件到客戶端
private void outputZipFile(File file) throws IOException, FileNotFoundException {
ZipEntry ze = null;
byte[] buf = new byte[1024];
int readLen = 0;
// 1.動態壓縮一個File到zip中
// 創建一個ZipEntry,并設置Name和其它的一些屬性
// 壓縮包中的路徑和文件名稱
ze = new ZipEntry("1\\1\\" + file.getName());
ze.setSize(file.length());
ze.setTime(file.lastModified());
// 將ZipEntry加到zos中,再寫入實際的文件內容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(file));
// 把數據寫入到客戶端
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
// 2.動態壓縮一個String到zip中
String customFile = "This is a text file.";
// 壓縮包中的路徑和文件名稱
ZipEntry cze = new ZipEntry(“1\\1\\” + "Test.txt");
zos.putNextEntry(cze);
// 利用ByteArrayInputStream把流數據寫入到客戶端
is = new ByteArrayInputStream(customFile.getBytes());
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
}