打包下载word+

/*打包下载*/
	@RequestMapping(params = "loadZip")
    public String Files(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		String id = request.getParameter("FSDYGCXXID");
		if (id == null) {
			id = dygc_id;
		}
		String[] Arr = id.split(",");
		String ids = "";
		for (String s : Arr) {
			ids += "'"+ s +"',";
		}
		if (Arr.length == 1 ) {
			String sql = String.format("select b.FILEPATH,b.FILENAME,a.FSPX,a.FSZH,a.FSPROINSID from t_dygcgl_dygcxx_qbs a LEFT JOIN t_sys_files b on a.ID = b.MAINTABLEID LEFT JOIN act_hi_procinst c on a.FSPROINSID = c.PROC_INST_ID_ WHERE a.FSDYGCXXID = '%s' and c.END_ACT_ID_ = 'endevent1'",id );
	        List<Map<String, Object>> lst= systemService.findForJdbc(sql) ;
			List<Map<String, Object>> files = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> name = new ArrayList<Map<String, Object>>();
			String root = request.getSession().getServletContext().getRealPath("/");
	        //File Allfile = new File(request.getSession().getServletContext().getRealPath("/"));
			int s = 1;
	        if(lst!=null && lst.size()>0){
		        for(int i =0;i<lst.size();i++){
		        	Map<String, Object> mp = new HashMap<String, Object>();
	        		Map<String, Object> mps = new HashMap<String, Object>();
		        	if (lst.get(i).get("FILEPATH") != null) {
		        		File file = new File(root+lst.get(i).get("FILEPATH"));
		        		String names = lst.get(i).get("FILENAME").toString();
		        		names = names + s;
  		        		s++;
		        		String fspx = lst.get(i).get("FSPX").toString();
		        		String fszh = lst.get(i).get("FSZH").toString();
			        	mp.put("PATH", file);
			        	mps.put("name", names);
			        	mps.put("fspx", fspx);
			        	mps.put("fszh", fszh);
			        	if(file.exists()){
			        		files.add(mp);
			        		name.add(mps);
			        	}
					}
		        }
		        
		        String sqlpdf = String.format("select b.FILEPATH,b.FILENAME,a.FSPX,a.FSZH,a.FSPROINSID from t_dygcgl_dygcxx_qbs a LEFT JOIN t_sys_files b on a.ID = b.MAINTABLEID LEFT JOIN act_hi_procinst c on a.FSPROINSID = c.PROC_INST_ID_ WHERE a.FSDYGCXXID = '%s' and c.END_ACT_ID_ = 'endevent1' and b.CODEID = 'qbsysb' ",id );
		        List<Map<String, Object>> lstpdf= systemService.findForJdbc(sqlpdf) ;
        		if(lstpdf!=null && lstpdf.size()>0){
      		       for(int i =0;i<lstpdf.size();i++){
	  		        	Map<String, Object> mp = new HashMap<String, Object>();
	  	        		Map<String, Object> mps = new HashMap<String, Object>();
	  		        	if (lstpdf.get(i).get("FILEPATH") != null) {
	  		        		String url = lstpdf.get(i).get("FILEPATH").toString();
			        		url = StringUtils.substringBefore(url,"."); 
			        		String urlname = url + ".pdf";
			        		File file = new File(root+urlname);
			        		String names = lstpdf.get(i).get("FILENAME").toString();
			        		String fspx = lstpdf.get(i).get("FSPX").toString();
			        		String fszh = lstpdf.get(i).get("FSZH").toString();
				        	mp.put("PATH", file);
				        	mps.put("name", names);
				        	mps.put("fspx", fspx);
				        	mps.put("fszh", fszh);
	  			        	if(file.exists()){
	  			        		files.add(mp);
	  			        		name.add(mps);
	  			        	}
	  					}
	  		        }
        		 }
	        }
			
	        String sqls = String.format("select fsdygcmc from t_dygcgl_dygcxx where id = '%s'",id );
	        Map<String, Object> map = systemService.findOneForJdbc(sqls);
	        String fileName = map.get("fsdygcmc").toString() + ".zip";
			
	        String userAgent = request.getHeader("user-agent");
	        userAgent = userAgent ==null?"":userAgent.toLowerCase();
	        String names = fileName;
	        try {
	            if(userAgent.contains("msie") ||userAgent.contains("trident")){
	                names = URLEncoder.encode(names, "UTF-8");
	            }else{
	                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer");  
	            }
	        } catch (Exception e) {
	        	response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer");  
	        }
	        
	        // 在服务器端创建打包下载的临时文件
	        String outFilePath = request.getSession().getServletContext().getRealPath("/") + "download/";
	        File file_1 =new File(outFilePath);    
	        //如果文件夹不存在则创建    
		      if  (!file_1 .exists()  && !file_1 .isDirectory())      
		      {       
		          System.out.println("//不存在");  
		          file_1 .mkdir();    
		      }
	        
	        File fileZip = new File(outFilePath + names);
	        // 文件输出流
	        FileOutputStream outStream = new FileOutputStream(fileZip);
	        // 压缩流
	        ZipOutputStream toClient = new ZipOutputStream(outStream);
	        //toClient.setEncoding("gbk");
	        zipFiles(files, toClient,name);
	        toClient.close();
	        outStream.close();
	       
	        this.downloadFiles(fileZip, response, true);
	        return null;
		}else {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		
		String[] Arrs = id.split(",");
		for (String FSDYGCXXID : Arrs) {
			
		String sql = String.format("select b.FILEPATH,b.FILENAME,a.FSPX,a.FSZH,a.FSPROINSID from t_dygcgl_dygcxx_qbs a LEFT JOIN t_sys_files b on a.ID = b.MAINTABLEID LEFT JOIN act_hi_procinst c on a.FSPROINSID = c.PROC_INST_ID_ WHERE a.FSDYGCXXID = '%s' and c.END_ACT_ID_ = 'endevent1'",FSDYGCXXID );
        List<Map<String, Object>> lst= systemService.findForJdbc(sql) ;
		List<Map<String, Object>> files = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> name = new ArrayList<Map<String, Object>>();
		String root = request.getSession().getServletContext().getRealPath("/");
        //File Allfile = new File(request.getSession().getServletContext().getRealPath("/"));
        if(lst!=null && lst.size()>0){
	        for(int i =0;i<lst.size();i++){
	        	if (lst.get(i).get("FILEPATH") != null) {
	        		Map<String, Object> mp = new HashMap<String, Object>();
	        		Map<String, Object> mps = new HashMap<String, Object>();
	        		File file = new File(root+lst.get(i).get("FILEPATH"));
	        		String names = lst.get(i).get("FILENAME").toString();
	        		String fspx = lst.get(i).get("FSPX").toString();
	        		String fszh = lst.get(i).get("FSZH").toString();
		        	mp.put("PATH", file);
		        	mps.put("name", names);
		        	mps.put("fspx", fspx);
		        	mps.put("fszh", fszh);
		        	if(file.exists()){
		        		files.add(mp);
		        		name.add(mps);
		        	}
				}
	        }
	        String sqlpdf = String.format("select b.FILEPATH,b.FILENAME,a.FSPX,a.FSZH,a.FSPROINSID from t_dygcgl_dygcxx_qbs a LEFT JOIN t_sys_files b on a.ID = b.MAINTABLEID LEFT JOIN act_hi_procinst c on a.FSPROINSID = c.PROC_INST_ID_ WHERE a.FSDYGCXXID = '%s' and c.END_ACT_ID_ = 'endevent1' and b.CODEID = 'qbsysb' ",FSDYGCXXID);
	        List<Map<String, Object>> lstpdf= systemService.findForJdbc(sqlpdf) ;
    		if(lstpdf!=null && lstpdf.size()>0){
  		       for(int i =0;i<lstpdf.size();i++){
  		        	Map<String, Object> mp = new HashMap<String, Object>();
  	        		Map<String, Object> mps = new HashMap<String, Object>();
  		        	if (lstpdf.get(i).get("FILEPATH") != null) {
  		        		String url = lstpdf.get(i).get("FILEPATH").toString();
		        		url = StringUtils.substringBefore(url,"."); 
		        		String urlname = url + ".pdf";
		        		File file = new File(root+urlname);
		        		String names = lstpdf.get(i).get("FILENAME").toString();
		        		String fspx = lstpdf.get(i).get("FSPX").toString();
		        		String fszh = lstpdf.get(i).get("FSZH").toString();
			        	mp.put("PATH", file);
			        	mps.put("name", names);
			        	mps.put("fspx", fspx);
			        	mps.put("fszh", fszh);
  			        	if(file.exists()){
  			        		files.add(mp);
  			        		name.add(mps);
  			        	}
  					}
  		        }
    		 }
        }
		
        String sqls = String.format("select fsdygcmc from t_dygcgl_dygcxx where id = '%s'",FSDYGCXXID );
        Map<String, Object> map = systemService.findOneForJdbc(sqls);
        String fileName = map.get("fsdygcmc").toString() + ".zip";
		
        String userAgent = request.getHeader("user-agent");
        userAgent = userAgent ==null?"":userAgent.toLowerCase();
        String names = fileName;
        try {
            if(userAgent.contains("msie") ||userAgent.contains("trident")){
                names = URLEncoder.encode(names, "UTF-8");
            }else{
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer");  
            }
        } catch (Exception e) {
        	response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer");  
        }
        
        // 在服务器端创建打包下载的临时文件
        String outFilePath = request.getSession().getServletContext().getRealPath("/") + "download/";
        File file_1 =new File(outFilePath);    
        //如果文件夹不存在则创建    
	      if  (!file_1 .exists()  && !file_1 .isDirectory())      
	      {       
	          System.out.println("//不存在");  
	          file_1 .mkdir();    
	      }
        
        File fileZip = new File(outFilePath + names);
        // 文件输出流
        FileOutputStream outStream = new FileOutputStream(fileZip);
        // 压缩流
        ZipOutputStream toClient = new ZipOutputStream(outStream);
        //toClient.setEncoding("gbk");
        zipFiles(files, toClient,name);
        toClient.close();
        outStream.close();
        Map<String, Object> mp = new HashMap<String, Object>();
        mp.put("fileZip", fileZip);
        list.add(mp);
		}
		
		String fileName = "单元工程word合并下载" + ".zip";
		
        String userAgent = request.getHeader("user-agent");
        userAgent = userAgent ==null?"":userAgent.toLowerCase();
        String names = fileName;
        try {
            if(userAgent.contains("msie") ||userAgent.contains("trident")){
                names = URLEncoder.encode(names, "UTF-8");
            }else{
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer");  
            }
        } catch (Exception e) {
        	response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer");  
        }
        
        // 在服务器端创建打包下载的临时文件
        String outFilePath = request.getSession().getServletContext().getRealPath("/") + "download/";
        File file_1 =new File(outFilePath);    
        //如果文件夹不存在则创建    
	      if  (!file_1 .exists()  && !file_1 .isDirectory())      
	      {       
	          System.out.println("//不存在");  
	          file_1 .mkdir();    
	      }
        
        File fileZip = new File(outFilePath + names);
        // 文件输出流
        FileOutputStream outStream = new FileOutputStream(fileZip);
        // 压缩流
        ZipOutputStream toClient = new ZipOutputStream(outStream);
        //toClient.setEncoding("gbk");
        zip(list, toClient);
        toClient.close();
        outStream.close();
        this.downloadFiles(fileZip, response, true);
        return null;
		}
    }
	public static void zip(List<Map<String, Object>> list, ZipOutputStream outputStream) throws IOException, ServletException {
        try {
            int size = list.size();
            // 压缩列表中的文件
            for (int i = 0; i < size; i++) {
                File file = (File) list.get(i).get("fileZip");
                zips(file,outputStream);
            }
        } catch (IOException e) {
            throw e;
        }
    }
	
	public static void zips(File file, ZipOutputStream outputStream) throws IOException, ServletException {
        try {
            if (file.exists()) {
                if (file.isFile()) {
                    FileInputStream inStream = new FileInputStream(file);
                    BufferedInputStream bInStream = new BufferedInputStream(inStream);
                    ZipEntry entrys = new ZipEntry(file.getName());
                    
                    ZipEntry entry = new ZipEntry(entrys);
                    outputStream.putNextEntry(entry);

                    final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
                    long streamTotal = 0; // 接受流的容量
                    int streamNum = 0; // 流需要分开的数量
                    int leaveByte = 0; // 文件剩下的字符数
                    byte[] inOutbyte; // byte数组接受文件的数据

                    streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
                    streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
                    leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量

                    if (streamNum > 0) {
                        for (int j = 0; j < streamNum; ++j) {
                            inOutbyte = new byte[MAX_BYTE];
                            // 读入流,保存在byte数组
                            bInStream.read(inOutbyte, 0, MAX_BYTE);
                            outputStream.write(inOutbyte, 0, MAX_BYTE); // 写出流
                        }
                    }
                    // 写出剩下的流数据
                    inOutbyte = new byte[leaveByte];
                    bInStream.read(inOutbyte, 0, leaveByte);
                    outputStream.write(inOutbyte);
                    outputStream.closeEntry(); // Closes the current ZIP entry
                    // and positions the stream for
                    // writing the next entry
                    bInStream.close(); // 关闭
                    inStream.close();
                }
            } else {
                throw new ServletException("文件不存在!");
            }
        } catch (IOException e) {
            throw e;
        }
    }

	
	
	public static void zipFiles(List<Map<String, Object>> files, ZipOutputStream outputStream, List<Map<String, Object>> name) throws IOException, ServletException {
        try {
            int size = files.size();
            // 压缩列表中的文件
            for (int i = 0; i < size; i++) {
                File file = (File) files.get(i).get("PATH");
                String qbsname = name.get(i).get("name").toString();
                String fspx = name.get(i).get("fspx").toString();
                String fszh = name.get(i).get("fszh").toString();
                zipFiles(file, outputStream, qbsname,fspx,fszh);
            }
        } catch (IOException e) {
            throw e;
        }
    }
	public static void zipFiles(File inputFile, ZipOutputStream outputstream, String qbsname,String fspx,String fszh) throws IOException, ServletException {
	        try {
	            if (inputFile.exists()) {
	                if (inputFile.isFile()) {
	                    FileInputStream inStream = new FileInputStream(inputFile);
	                    BufferedInputStream bInStream = new BufferedInputStream(inStream);
	                    ZipEntry entrys = new ZipEntry(inputFile.getName());
	                    
	                    String entry1 = entrys.toString();
	                    entry1 = StringUtils.substringAfter(entry1,"."); 
	                    String pathname = qbsname+"_"+fszh+"_("+ fspx+ ")."+entry1;
	                    ZipEntry entry = new ZipEntry(pathname);
	                    outputstream.putNextEntry(entry);
	
	                    final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
	                    long streamTotal = 0; // 接受流的容量
	                    int streamNum = 0; // 流需要分开的数量
	                    int leaveByte = 0; // 文件剩下的字符数
	                    byte[] inOutbyte; // byte数组接受文件的数据
	
	                    streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
	                    streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
	                    leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量
	
	                    if (streamNum > 0) {
	                        for (int j = 0; j < streamNum; ++j) {
	                            inOutbyte = new byte[MAX_BYTE];
	                            // 读入流,保存在byte数组
	                            bInStream.read(inOutbyte, 0, MAX_BYTE);
	                            outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
	                        }
	                    }
	                    // 写出剩下的流数据
	                    inOutbyte = new byte[leaveByte];
	                    bInStream.read(inOutbyte, 0, leaveByte);
	                    outputstream.write(inOutbyte);
	                    outputstream.closeEntry(); // Closes the current ZIP entry
	                    // and positions the stream for
	                    // writing the next entry
	                    bInStream.close(); // 关闭
	                    inStream.close();
	                }
	            } else {
	                throw new ServletException("文件不存在!");
	            }
	        } catch (IOException e) {
	            throw e;
	        }
	    }
	
	public void downloadFiles(File file,HttpServletResponse response,boolean isDelete) {
	    try {
	        // 以流的形式下载文件。
	        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
	        byte[] buffer = new byte[fis.available()];
	        fis.read(buffer);
	        fis.close();
	        // 清空response
	        
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        response.setContentType("application/octet-stream");
	        response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
	        if(isDelete)
	        {
	            file.delete();        //是否将生成的服务器端文件删除
	        }
	     } 
	     catch (IOException ex) {
	        ex.printStackTrace();
	    }
	}

猜你喜欢

转载自blog.csdn.net/qq_43420577/article/details/83061252
今日推荐