1. 程式人生 > >java實現檔案打包下載

java實現檔案打包下載

業務場景:

          從A伺服器通過SFTP將檔案下載到應用伺服器B,需要將檔案從應用伺服器B下載到使用者本地(檔案和應用都在B伺服器)

想法:

          1. 想要通過FTP連線B伺服器下載,但是FTP只能下載到應用所在的本地,也就是隻能下載到下載到B伺服器,無法下載到使用者本地。

          2. 通過普通的下載方式,用檔案流通過response下載,但是資料夾內有多個檔案,無法同時下載

實現:

          採用將多個檔案打包下載

          

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
        //通過工號和日期去獲取相應的資料夾路徑
    	String usercode = request.getParameter("usercode");
    	String date = request.getParameter("date");
        
    	String formPath = "/tmp/ENongXian/"+usercode+"/"+date;
        //遍歷這個路徑下的所有檔名
    	List fileNames = this.getFileName(formPath);
        //如果找不到檔案  返回not found file
    	if(fileNames == null||fileNames.size()==0){
    		PrintWriter out = response.getWriter();
    		response.setContentType("text/html; charset=GBK");//注意text/html,和application/html
    		out.print("<html><body><script type='text/javascript'>alert('not found file');</script></body></html>");
    		out.flush();
    		out.close();
    	}else{
            //開始批量壓縮下載
    		ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); 
        	response.setContentType("APPLICATION/OCTET-STREAM");  
        	response.setHeader("Content-Disposition","attachment; filename="+this.getZipFilename());  
        	System.out.println("in BatchDownload................"); 
    		File[] files = new File[fileNames.size()];  
        	for(int i=0;i<files.length;i++){
        		String filename = fileNames.get(i).toString();
        		files[i] = new File(formPath+"/"+filename);
        	}
            將檔案進行壓縮
        	zipFile(files, "", zos);     
        	zos.flush();     
        	zos.close();   
    	}
    	  
    }
    
    private void zipFile(File[] subs, String baseName, ZipOutputStream zos) throws IOException {       
        for (int i=0;i<subs.length;i++) {  
         File f=subs[i];  
         zos.putNextEntry(new ZipEntry(baseName + f.getName()));     
         FileInputStream fis = new FileInputStream(f);     
         byte[] buffer = new byte[1024];     
         int r = 0;     
         while ((r = fis.read(buffer)) != -1) {     
             zos.write(buffer, 0, r);     
         }     
         fis.close();   
        }  
   }  
   private String getZipFilename(){  
    Date date=new Date();  
    String s=date.getTime()+".zip";  
    return s;  
   }  
   
	public List getFileName(String filePath){
		File file = new File(filePath);
		List fileNameList = new ArrayList();
		File[] fileList = file.listFiles();
		if(fileList == null || fileList.length ==0){
			return null;
		}
		for(int i=0;i<fileList.length;i++){
			if("txt".equals(fileList[i].getName().substring(fileList[i].getName().lastIndexOf(".") + 1))){
				continue;
			}
			if(fileList[i].isFile()){
				String fileName = fileList[i].getName();
				fileNameList.add(fileName);
			}			
		}
		return fileNameList;
	}