1. 程式人生 > >java web 實現多個檔案壓縮下載

java web 實現多個檔案壓縮下載

檔案下載時,我們可能需要一次下載多個檔案。批量下載檔案時,需要將多個檔案打包為zip,然後再下載。實現思路有兩種:一是將所有檔案先打包壓縮為一個檔案,然後下載這個壓縮包,二是一邊壓縮一邊下載,將多個檔案逐一寫入到壓縮檔案中。我這裡實現了邊壓縮邊下載。

下載樣式:

點選下載按鈕,會彈出下載框:

下載後就有一個包含剛剛選中的兩個檔案:

程式碼實現:

FileBean

public class FileBean implements Serializable {
	private Integer fileId;// 主鍵

	private String filePath;// 檔案儲存路徑

	private String fileName;// 檔案儲存名稱

	public FileBean() {

	}

	public Integer getFileId() {
		return fileId;
	}

	public void setFileId(Integer fileId) {
		this.fileId = fileId;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

}

控制層:
@RequestMapping(value = "/download", method = RequestMethod.GET)
	public String download(String id, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String str = "";
		if (id != null && id.length() != 0) {
			int index = id.indexOf("=");
			str = id.substring(index + 1);
			String[] ids = str.split(",");
			ArrayList<FileBean> fileList = new ArrayList<FileBean>();
			for (int i = 0; i < ids.length; i++) {// 根據id查詢genericFileUpload,得到檔案路徑以及檔名
				GenericFileUpload genericFileUpload = new GenericFileUpload();
				genericFileUpload = genericFileUploadService.find(Long.parseLong(ids[i]));
				FileBean file = new FileBean();
				file.setFileName(genericFileUpload.getFileName());
				file.setFilePath(genericFileUpload.getFilePath());
				fileList.add(file);
			}
			//設定壓縮包的名字
	        //解決不同瀏覽器壓縮包名字含有中文時亂碼的問題
			String zipName = "download.zip";
			response.setContentType("APPLICATION/OCTET-STREAM");
			response.setHeader("Content-Disposition", "attachment; filename="+ zipName);
			//設定壓縮流:直接寫入response,實現邊壓縮邊下載
			ZipOutputStream zipos  =null;
			try{
				zipos=new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
				zipos.setMethod(ZipOutputStream.DEFLATED);//設定壓縮方法 
			}catch(Exception e){
				e.printStackTrace();
			}
			DataOutputStream os=null;
			//迴圈將檔案寫入壓縮流
			for(int i=0;i<fileList.size();i++){
				String filePath=fileList.get(i).getFilePath();
				String fileName=fileList.get(i).getFileName();
				File file=new File(filePath+"/"+fileName);//要下載檔案的路徑
				try{
					//新增ZipEntry,並ZipEntry中寫入檔案流
	                //這裡,加上i是防止要下載的檔案有重名的導致下載失敗
					zipos.putNextEntry(new ZipEntry(i+fileName));
					os=new DataOutputStream(zipos);
					InputStream is=new FileInputStream(file);
					byte[] b = new byte[100];
	                int length = 0;
	                while((length = is.read(b))!= -1){
	                    os.write(b, 0, length);
	                }
	                is.close();
	                zipos.closeEntry();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			 //關閉流
	        try {
	            os.flush();
	            os.close();
	            zipos.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }    		
			
		}
		return "redirect:list.jhtml";
	}