1. 程式人生 > >java實現檔案壓縮下載----壓縮下載zip

java實現檔案壓縮下載----壓縮下載zip

檔案壓縮下載

Controller層:

           
/**
 *檔案壓縮下載
 *billname:檔名
 *filename:檔案存放路徑
 */
 public void downloadsource(HttpServletResponse response,String billname,String filename) throws FileNotFoundException, IOException{
		        //響應頭的設定
		        response.reset();
		        response.setCharacterEncoding("utf-8");
		        response.setContentType("multipart/form-data");
		       
		        //設定壓縮包的名字
		         //解決不同瀏覽器壓縮包名字含有中文時亂碼的問題
		        String downloadName = billname+".zip";
		        //返回客戶端瀏覽器的版本號、型別
		        String agent = request.getHeader("USER-AGENT");  
		        try {
		        	//針對IE或者以IE為核心的瀏覽器:  
		            if (agent.contains("MSIE")||agent.contains("Trident")) {
		                downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
		            } else {
		            	//非IE瀏覽器的處理:
		                downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");
		            }
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");

		        //設定壓縮流:直接寫入response,實現邊壓縮邊下載
		        ZipOutputStream zipos = null;
		        try {
		            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
		            zipos.setMethod(ZipOutputStream.DEFLATED); //設定壓縮方法 
		        } catch (Exception e) {
		            e.printStackTrace();
		        }

		        //迴圈將檔案寫入壓縮流
		        DataOutputStream os = null;
		       
		        		String modipath = request.getSession().getServletContext().getRealPath("/vod/mp4/"+filename);
		        		File file = new File(modipath);
		        		if(file.exists()){
					        			
					        			
		        			try {
		        				//新增ZipEntry,並ZipEntry中寫入檔案流
		        				//這裡,加上i是防止要下載的檔案有重名的導致下載失敗
		        				zipos.putNextEntry(new ZipEntry(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 (IOException e) {
		        				e.printStackTrace();
		        			} 
		        		}
			     //關閉流
		        try {
		            os.flush();
		            os.close();
		            zipos.close();
		        } catch (IOException e) {
		            e.printStackTrace();
		        }    

		    }