生成zip压缩文件下载,带文件夹结构(方法二)

工具同方法一:ant (org.apache.tools.ant)

方法一中,生成的压缩文件方式为:先生成对应的文件结构,把整个文件夹生成zip文件

而在方法二为直接写入zip文件,再对zip文件进行下载删除操作

			String pid = request.getParameter("pid");
			if(StringUtils.isNotBlank(pid)) {
				
				// 项目的文件
				List<Map<String,Object>> projectFileList = baseAreaManager.findSql("select * from xxx t where 1=1 and t.pro_id = '" + pid + "'");
				// 单体的文件
				List<Map<String,Object>> itemFileList = baseAreaManager.findSql("select * from xxx t where 1=1 and t.pro_id = '" + pid + "'");

				
				
				
				ServletContext context = servletContext;
                // 临时zip路径
				String FilePath = "/upload/tempZip/";  
				
				response.setContentType("text/html; charset=UTF-8");
				HttpSession session = request.getSession();
				String foderName = request.getParameter("foderName");
				
				String downloadpath = context.getRealPath(File.separator);
				
				String tmpFileName = foderName+".zip";
				//String tmpFileName = "File.zip"; 
		        byte[] buffer = new byte[1024];    
		        String strZipPath = downloadpath + FilePath + tmpFileName;    
		        try {
		        	// 创建临时目录
		        	if (StringUtils.isNotBlank(downloadpath + FilePath)) {
						File file = new File(downloadpath + FilePath);
						if (!file.exists()) {
							file.mkdirs();
						}
					}
		        	// 创建压缩文件
		            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(    
		                    strZipPath));
		            // 防止中文乱码(经过多次试验发现必须写在前面,不然会导致第一个写入的文件乱码)
		            out.setEncoding("GBK");
		            
		            // 先压缩项目的文件
		            for (Map<String,Object> map : projectFileList) {
						String folderName = "其他文件";
						if("qq".equals(map.get("1"))) {
							folderName = "前期文件";
						}else if("zb".equals(map.get("1"))) {
							folderName = "招标文件";
						}else if("jg".equals(map.get("1"))) {
							folderName = "竣工文件";
						}else if("project_file_type_shenji".equals(map.get("1"))) {
							folderName = "审计文件";
						}
						try {
							// 读取文件
		            		 FileInputStream fis = new FileInputStream(new File(downloadpath +(String) map.get("1"))); 
		            		 String fileName = folderName + File.separator +  (String) map.get("1");
		            		 // zip添加文件的名字
			            	 ZipEntry ze=new ZipEntry(fileName);
			            	
			                 out.putNextEntry(ze);
			            	 
			                 //设置压缩文件内的字符编码,不然会变成乱码    
			                 out.setEncoding("GBK");  

			            	 //out.setEncoding("UTF-8"); 
			                 int len;    
			                 // 读入需要下载的文件的内容,打包到zip文件    
			                 while ((len = fis.read(buffer)) > 0) {    
			                     out.write(buffer, 0, len);    
			                 }    
			                 //out.flush();
			                 out.setEncoding("GBK");  
			                 out.closeEntry();
			                 fis.close();    
						} catch (Exception e) {
							//没找到文件 跳过
							e.printStackTrace();
						}
					}
		            
		            // 单体文件
		            for (Map<String,Object> map : itemFileList) {
						String folderName = "其他文件";
						if("kh".equals(map.get("1"))) {
							folderName = "开工文件";
						}else if("zt".equals(map.get("1"))) {
							folderName = "主体完成文件";
						}
						
						try {
		            		 FileInputStream fis = new FileInputStream(new File(downloadpath +(String) map.get("1"))); 
			            	 ZipEntry ze=new ZipEntry(folderName + File.separator +  (String) map.get("1"));
			            	
			                 out.putNextEntry(ze);
			            
			                 //设置压缩文件内的字符编码,不然会变成乱码    
			                 out.setEncoding("GBK");  
			            	 //out.setEncoding("UTF-8"); 
			                 int len;    
			                 // 读入需要下载的文件的内容,打包到zip文件    
			                 while ((len = fis.read(buffer)) > 0) {    
			                     out.write(buffer, 0, len);    
			                 }    
			                 //out.flush();
			                 out.closeEntry();
			                 
			                 fis.close();    
						} catch (Exception e) {
							//没找到文件 跳过
							e.printStackTrace();
						}
					}
		            
		            out.close();    
		            //this.downFile(response, tmpFileName); 
                    // 文件下载操作  
		            this.downTmpFile(response,tmpFileName);、
                    // 删除文件
		            new File(downloadpath + FilePath + tmpFileName).delete();
		        } catch (Exception e) {    
		           e.printStackTrace();
		            System.out.println("文件下载出错");
		        }    
		        //return null;   
			}
		}

文件下载:

/**   
	     * 文件下载   
	     * @param response   
	     * @param str   
	     */    
	    private void downTmpFile(HttpServletResponse response, String str) {
	    	String FilePath = "/upload/tempZip/";  
	    	
	        try {
	        	ServletContext context = servletContext;
	        	String downloadpath = context.getRealPath(File.separator);
	            String path = downloadpath + FilePath + 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=" + new String( str.getBytes("gb2312"), "ISO8859-1" ) ); // 设置头部信息,防止乱码     
	                //response.setCharacterEncoding("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("../error.jsp");    
	            }    
	        } catch (IOException e) {    
	        	System.out.println("文件下载出错");
	        }    
	    }    

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值