`
dengwenwei121
  • 浏览: 36730 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
文章分类
社区版块
存档分类
最新评论

java多文件压缩下载

 
阅读更多
页面端:
 function jqchk(){  //jquery获取复选框值
	  var s='';
	  $('input[name="zydName"]:checked').each(function(){
	    s+=$(this).val()+',';
	  }); 
	  if(s.length>0)
	   {
		  s=s.substring(0,s.length-1);
		  location.href="$!webPath/usercenter/show/res/downAll.htm?ids="+s+"";
	   }
	  else
	  {
		  alert("请选中需要下载的资源单!");
	  }
 }

服务端:

// 下载选中的
	@SuppressWarnings({ "deprecation", "rawtypes", "null", "unchecked" })
	@RequestMapping({ "/downAll.htm" })
	public void downExcelAll(HttpServletRequest request,
			HttpServletResponse response, String ids) {
		String[] strID = null;
		if (ids != null) {
			strID = ids.split(",");
		}

		String accessoryId = "";
		String tmpFilePath = "";
		List filePaths = new ArrayList();
		if (strID != null) {
			for (int i = 0; i < strID.length; i++) {
				Res res = resImpl.getObjById(strID[i]);
				if (CommUtil.isNotNull(res)) {
					accessoryId = res.getAccessoryId();
					if (CommUtil.isNotNull(accessoryId)) {
						Accessory accessory = accessoryService
								.getObjById(accessoryId);
						String ac_path = accessory.getAcPath();
						String fileName = accessory.getName();
						if (tmpFilePath == null || "".equals(tmpFilePath)) {
							tmpFilePath = request.getRealPath("") + ac_path;
						}
						String filePath = request.getRealPath("") + ac_path
								+ fileName;
						filePaths.add(filePath);
						int downNum = res.getDownNum();
						downNum += 1;
						res.setDownNum(downNum);
						resImpl.update(res);
					}
				}
			}
		}

		this.downAll(request, response, tmpFilePath, filePaths);

	}
	
	@SuppressWarnings({ "rawtypes", "unchecked", "null" })
	public String downAll(HttpServletRequest request,
			HttpServletResponse response,String tmpFilePath,List  filePaths) {    
        //生成的ZIP文件名为Demo.zip    
        String tmpFileName = "zyd.zip";    
        byte[] buffer = new byte[1024];    
        String strZipPath = tmpFilePath + tmpFileName;    
        try {    
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
           List fielpathss=new ArrayList();
            if(filePaths!=null)
            {
            	 for (int i = 0; i < filePaths.size(); i++) {
   				  if(new File(filePaths.get(i).toString()).exists())
   				  {
   					fielpathss.add(filePaths.get(i));
   				  }
   			    }
            }
            // 需要同时下载多个文件   
            File[] file1 =null;
             if(fielpathss.size()>0)
             {
            	 file1=new File[fielpathss.size()]; 
				 for (int i = 0; i < fielpathss.size(); i++) {
					  file1[i]=new File(fielpathss.get(i).toString()); 
				}            	
             }
             if(file1!=null)
             {
            	 for (int i = 0; i < file1.length; i++) {    
                     FileInputStream fis = new FileInputStream(file1[i]);    
                     out.putNextEntry(new ZipEntry(file1[i].getName()));    
                     //设置压缩文件内的字符编码,不然会变成乱码    
                     out.setEncoding("UTF-8");    
                     int len;    
                     // 读入需要下载的文件的内容,打包到zip文件    
                     while ((len = fis.read(buffer)) > 0) {    
                         out.write(buffer, 0, len);    
                     }    
                     out.closeEntry();    
                     fis.close();    
                 }    
                 out.close();   
             }
            this.downFile(response,request,strZipPath,tmpFileName);    
        } catch (Exception e) {    
            logger.error("文件下载出错", e);    
        }    
        return null;    
    }   
    /**   
     * 文件下载   
     * @param response   
     * @param str   
     */    
    @SuppressWarnings("deprecation")
	private void downFile(HttpServletResponse response,HttpServletRequest request,String str,String tmpFileName) {    
        try {    
            String path =str;    
            File file = new File(path);    
            if (file.exists()) {    
                InputStream ins = new FileInputStream(path);    
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面    
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流    
                BufferedOutputStream bouts = new BufferedOutputStream(outs);    
                response.setContentType("application/x-download");// 设置response内容的类型    
                response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode(tmpFileName, "UTF-8"));// 设置头部信息    
                int bytesRead = 0;    
                byte[] buffer = new byte[8192];    
                // 开始向网络传输文件流    
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {    
                    bouts.write(buffer, 0, bytesRead);    
                }    
                bouts.flush();// 这里一定要调用flush()方法    
                ins.close();    
                bins.close();    
                outs.close();    
                bouts.close();    
            } else {    
            	 response.sendRedirect(""+request.getRealPath("")+"/usercenter/show/res/downerror.htm");
            }    
        } catch (IOException e) {    
            e.printStackTrace();
        }    
    }
pom依赖:

        <dependency>
            <groupId>ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.7.0</version>
        </dependency>


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics