多個文件,目錄不同,通過條件查詢如何進行打包下載呢?
1.利用ZipEntry進i行文件的壓縮
2.前臺jsp傳入需要打包下載的一系列的文件的路徑(數組類型)。因爲是在checkBox中,表單提交會自動將其定義成數組。只需要將name名稱命名成後臺需要得到的路徑數組名稱
比如前臺
downLoadZip.jsp
--------checkBox處代碼-------------------------------
利用iterator迭代出來的filePath
<input type="checkbox" name="downLoadPaths"
value='<s:property value="filePath"/>'/>
後臺Action
private String[] downLoadPaths;
對downLoadPaths進行遍歷,打包。。。。
代碼:
- /**
- * 批量下載(壓縮成zip,然後下載)。不創建臨時文件
- *
- * @author Cloudy
- *
- */
- @Namespace("xxxxxx")
- public class DownZipAction {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- // 傳遞一個List<String>()對象傳值路徑合集
- private String[] downLoadPaths;
- private OutputStream res;
- private ZipOutputStream zos;
- private String outPath;
- // Action主方法
- @Action(value="DownLoadZip",results={@Result(name="nodata",location="/error.jsp"),
- @Result(name="success",location="xxxx.jsp")})
- public String downLoadZip() throws Exception {
- // 有數據可以下載
- if (downLoadPaths.length != 0) {
- // 進行預處理
- preProcess();
- } else {
- // 沒有文件可以下載,返回nodata
- return "nodata";
- }
- // 處理
- writeZip(downLoadPaths);
- // 後處理關閉流
- afterProcess();
- return SUCCESS;
- }
- // 壓縮處理
- public void writeZip(String[] downLoadPaths) throws IOException {
- byte[] buf = new byte[8192];
- int len;
- for (String filename : downLoadPaths) {
- File file = new File(filename);
- if (!file.isFile())
- continue;
- ZipEntry ze = new ZipEntry(file.getName()); //apache jar的ZipEntry
- zos.putNextEntry(ze);
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
- while ((len = bis.read(buf)) > 0) {
- zos.write(buf, 0, len);
- }
- bis.close();
- zos.closeEntry();
- }
- }
- // 預處理
- public void preProcess() throws Exception {
- HttpServletResponse response = ServletActionContext.getResponse();
- res = response.getOutputStream();
- // 清空輸出流(在迅雷下載不會出現一長竄)
- response.reset();
- // 設定輸出文件頭
- response.setHeader("Content-Disposition", "attachment;filename=document.zip");
- response.setContentType("application/zip");
- zos = new ZipOutputStream(res);
- }
- // 後處理
- public void afterProcess() throws IOException {
- zos.close();
- res.close();
- }
- public OutputStream getRes() {
- return res;
- }
- public void setRes(OutputStream res) {
- this.res = res;
- }
- public ZipOutputStream getZos() {
- return zos;
- }
- public void setZos(ZipOutputStream zos) {
- this.zos = zos;
- }
- public String[] getDownLoadPaths() {
- return downLoadPaths;
- }
- public void setDownLoadPaths(String[] downLoadPaths) {
- this.downLoadPaths = downLoadPaths;
- }
- public String getOutPath() {
- return outPath;
- }
- public void setOutPath(String outPath) {
- this.outPath = outPath;
- }
- }