Quellcode durchsuchen

项目文件批量下载

user5 vor 4 Jahren
Ursprung
Commit
c5e82e7f90

+ 203 - 0
src/main/java/com/jeeplus/modules/ruralprojectrecords/service/RuralProjectRecordsService.java

@@ -5,6 +5,7 @@ package com.jeeplus.modules.ruralprojectrecords.service;
 
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
+import com.jeeplus.common.config.Global;
 import com.jeeplus.common.persistence.Page;
 import com.jeeplus.common.service.CrudService;
 import com.jeeplus.common.utils.Collections3;
@@ -14,10 +15,16 @@ import com.jeeplus.common.utils.MenuStatusEnum;
 import com.jeeplus.modules.act.entity.Act;
 import com.jeeplus.modules.act.service.ActTaskService;
 import com.jeeplus.modules.act.utils.ProcessDefCache;
+import com.jeeplus.modules.projectAccessory.dao.ProjectTemplateDao;
+import com.jeeplus.modules.projectAccessory.entity.ProjectAccessoryRelationInfo;
+import com.jeeplus.modules.projectAccessory.entity.ProjectTemplateInfo;
+import com.jeeplus.modules.projectAccessory.service.ProjectAccessoryRelationService;
+import com.jeeplus.modules.projectAccessory.service.ProjectTemplateService;
 import com.jeeplus.modules.projectcontentinfo.dao.ProjectReportDataDao;
 import com.jeeplus.modules.projectcontentinfo.dao.ProjectcontentinfoDao;
 import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportData;
 import com.jeeplus.modules.projectcontentinfo.entity.Projectcontentinfo;
+import com.jeeplus.modules.projectcontentinfo.service.ProjectReportDataService;
 import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
 import com.jeeplus.modules.ruralprojectrecords.dao.RuralProjectClientLinkmanDao;
 import com.jeeplus.modules.ruralprojectrecords.dao.RuralProjectRecordsDao;
@@ -33,6 +40,8 @@ import com.jeeplus.modules.sys.service.OfficeService;
 import com.jeeplus.modules.sys.service.WorkattachmentService;
 import com.jeeplus.modules.sys.utils.DictUtils;
 import com.jeeplus.modules.sys.utils.UserUtils;
+import com.jeeplus.modules.utils.SftpClientUtil;
+import com.jeeplus.modules.utils.ZipCompressUtil;
 import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
 import com.jeeplus.modules.workactivity.entity.Activity;
 import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
@@ -65,8 +74,14 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLEncoder;
 import java.text.SimpleDateFormat;
 import java.util.*;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
 
 /**
  * 项目登记Service
@@ -119,6 +134,21 @@ public class RuralProjectRecordsService extends CrudService<RuralProjectRecordsD
     private WorkActivityProcessDao workActivityProcessDao;
     @Autowired
 	private ProjectReportDataDao projectReportDataDao;
+    @Autowired
+	private ProjectReportDataService projectReportDataService;
+	@Autowired
+	private ProjectAccessoryRelationService projectAccessoryRelationService;
+	@Autowired
+	private ProjectTemplateDao projectTemplateDao;
+
+
+	/**
+	 * 获取项目附件模板类型
+	 * @return
+	 */
+	public static List<MainDictDetail> attachmentTemplateList(){
+		return  DictUtils.getMainDictList("attachment_template_type");
+	}
 
 	private static byte[] SYN_BYTE = new byte[0];
 
@@ -1442,4 +1472,177 @@ public class RuralProjectRecordsService extends CrudService<RuralProjectRecordsD
 			dao.updateProjectReportedState(idList);
 		}
 	}
+
+	/**
+	 * 项目相应文件批量下载并压缩
+	 * @param idList
+	 */
+	public String exportAll(List<String> idList) throws Exception {
+		//设置下载的压缩包名(固定字符+时间戳)
+		long timeMillis = System.currentTimeMillis();
+		String fileLocality = "项目附件_"+ timeMillis;
+		//判定当前系统
+		String path = null;
+		if(System.getProperty("os.name").toLowerCase().contains("win")){
+			path = Global.getConfig("remoteServer.winDirectory");
+		}else{
+			path = Global.getConfig("remoteServer.directory");
+		}
+		path = path + "/" + fileLocality;
+		//检查该路径对应的目录是否存在. 如果不存在则创建目录
+		File dir=new File(path);
+		if (!dir.exists()) {
+			dir.mkdirs();
+		}
+		//遍历项目id并查询对应数据信息
+		for (String projectId: idList) {
+			//获取项目信息
+			RuralProjectRecords records = this.getQueryProjectUsers(projectId);
+			//根据项目id查询项目报告信息
+			ProjectReportData projectReportData = projectReportDataService.getReportDataByProjectId(records.getId());
+			projectReportData = projectReportDataService.get(projectReportData.getId());
+			ProjectAccessoryRelationInfo relateInfo = new ProjectAccessoryRelationInfo();
+
+			//添加项目类型
+			relateInfo.setAttachmentProjectType(records.getProjectType());
+			relateInfo.setAttachmentProjectSort(records.getAttachmentProjectSort());
+
+			//查看送审金额是否为500w以上金额
+			Integer approvalMoney = projectAccessoryRelationService.decideAttachmentProjectApprovalMoney(projectReportData.getReviewFee());
+			if(0 == approvalMoney){
+				//金额为0
+				relateInfo.setAttachmentProjectApprovalMoney(null);
+			}else if(1 == approvalMoney){
+				//500w以下金额状态
+				relateInfo.setAttachmentProjectApprovalMoney("1");
+			}else{
+				//500w以上金额状态
+				relateInfo.setAttachmentProjectApprovalMoney("2");
+			}
+			//添加报告类型
+			relateInfo.setRequiredStage(1);
+			relateInfo.setId(records.getId());
+			//查询报告文件、依据性文件、其他文件必填列表以及数据
+			List<MainDictDetail> mainDictDetails = this.attachmentTemplateList();
+			List<ProjectTemplateInfo> projectTemplateList = null;
+			String downloadPath = path + "/" + records.getProjectName();
+			for (MainDictDetail mainDict : mainDictDetails) {
+				relateInfo.setAttachType(mainDict.getValue());
+				File dirFile = null;
+				switch (mainDict.getValue()) {
+					case "11":
+						dirFile=new File(downloadPath+"/成果文件");
+						projectTemplateList = Lists.newArrayList();
+						projectTemplateList = this.getProjectTemplateList(relateInfo);
+						this.disposeFileList(projectTemplateList,dirFile.getPath());
+						break;
+					case "12":
+						dirFile=new File(downloadPath+"/依据性资料");
+						projectTemplateList = Lists.newArrayList();
+						projectTemplateList = this.getProjectTemplateList(relateInfo);
+						this.disposeFileList(projectTemplateList,dirFile.getPath());
+						break;
+					case "13":
+						dirFile=new File(downloadPath+"/其他文件");
+						projectTemplateList = Lists.newArrayList();
+						projectTemplateList = this.getProjectTemplateList(relateInfo);
+						this.disposeFileList(projectTemplateList,dirFile.getPath());
+						break;
+				}
+
+			}
+
+		}
+		//处理完之后进行打包压缩并删除之前的文件
+		ZipCompressUtil zipUtil = new ZipCompressUtil();
+		File resultFile = new File(path);
+		File file = zipUtil.zipCompress(resultFile, true);
+		return file.getPath();
+	}
+
+	/**
+	 * 下载压缩文件
+	 * @param filePath
+	 * @param response
+	 */
+	public void downloadZipFile(String filePath,HttpServletResponse response){
+		File file = new File(filePath);
+		// 取得文件名。
+		String fileName = file.getName();
+		InputStream in = null;
+		try {
+			fileName = URLEncoder.encode(fileName,"UTF8");
+			in = new FileInputStream(file);
+			response.reset();//重置 响应头
+			response.setCharacterEncoding("UTF-8");
+			response.setContentType("application/x-download");
+			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
+
+			byte[] b = new byte[1024];
+			int len;
+			while ((len = in.read(b)) > 0){
+				response.getOutputStream().write(b, 0, len);
+			}
+			in.close();
+			response.getOutputStream().close();
+		}catch (IOException e) {
+			throw new RuntimeException(e);
+		}
+		finally {
+			//路径是个文件且不为空时删除文件
+			if(file.isFile()&&file.exists()){
+				file.delete();
+			}
+		}
+	}
+
+	/**
+	 * 处理文件信息
+	 * @param projectTemplateList
+	 * @param downloadPath
+	 */
+	public void disposeFileList(List<ProjectTemplateInfo> projectTemplateList,String downloadPath) throws IOException {
+		SftpClientUtil sftpClientUtil = new SftpClientUtil();
+		for (ProjectTemplateInfo info: projectTemplateList) {
+			List<WorkClientAttachment> workAttachments = info.getWorkAttachments();
+			for (WorkClientAttachment attachment:workAttachments) {
+				sftpClientUtil.downloadRuralProject(attachment.getUrl().substring(0,attachment.getUrl().lastIndexOf("/")),attachment.getUrl().substring(attachment.getUrl().lastIndexOf("/") + 1, attachment.getUrl().length()),downloadPath,attachment.getAttachmentName());
+			}
+		}
+	}
+
+
+	public List<ProjectTemplateInfo> getProjectTemplateList(ProjectAccessoryRelationInfo projectTemplateInfo){
+		//查询所有被选择为必填项展示列,并查询附件信息
+		List<ProjectTemplateInfo> projectTemplateList = projectTemplateDao.getProjectTemplateList(projectTemplateInfo);
+		for (ProjectTemplateInfo info: projectTemplateList) {
+			WorkClientAttachment attchment = new WorkClientAttachment();
+			attchment.setProjectId(projectTemplateInfo.getId());
+			attchment.setAttachmentId(info.getId());
+			List<WorkClientAttachment> attachments = workClientAttachmentDao.getList(attchment);
+			info.setWorkAttachments(attachments);
+			//判断是否为必填项,若为必填项则添加必填判定字段
+			if(info.getRequiredStage() == projectTemplateInfo.getRequiredStage()){
+				info.setMustFlag(1);
+			} else {
+				info.setMustFlag(0);
+			}
+		}
+		//查询没有被选择必填项的数据并查询是否已经上传附件,若有则添加到展示列中
+		List<ProjectTemplateInfo> otherProjectTemplateList = projectTemplateDao.projectAccessoryListByParentId(projectTemplateInfo);
+		for (ProjectTemplateInfo otherInfo: otherProjectTemplateList) {
+			WorkClientAttachment attchment = new WorkClientAttachment();
+			attchment.setProjectId(projectTemplateInfo.getId());
+			attchment.setAttachmentId(otherInfo.getId());
+			List<WorkClientAttachment> attachments = workClientAttachmentDao.getList(attchment);
+			if(attachments.size()>0){
+				otherInfo.setWorkAttachments(attachments);
+
+				otherInfo.setMustFlag(0);
+				projectTemplateList.add(otherInfo);
+			}
+		}
+
+		return projectTemplateList;
+	}
 }

+ 10 - 7
src/main/java/com/jeeplus/modules/ruralprojectrecords/web/RuralCostProjectMessageController.java

@@ -437,32 +437,35 @@ public class RuralCostProjectMessageController extends BaseController {
         projectcontent.setProjectReportData(projectReportData);
         //根据条件查询附件必填项
         //判断项目类别是否为打包项目(1:打包项目,0:非打包项目)
-        Integer projectSort = projectAccessoryRelationService.decideAttachmentProjectSort(ruralProjectRecords.getAttachmentProjectSort());
+        /*Integer projectSort = projectAccessoryRelationService.decideAttachmentProjectSort(ruralProjectRecords.getAttachmentProjectSort());
 
         Boolean flag = false;
         //如果是打包项目或者报告送审价不为null则可进行查询附件类型
         if(1 == projectSort || null != projectReportData.getReviewFee()){
             flag = true;
         }
-        if(flag) {
+        if(flag) {*/
             ProjectAccessoryRelationInfo relateInfo = new ProjectAccessoryRelationInfo();
             //添加项目类型
             relateInfo.setAttachmentProjectType(ruralProjectRecords.getProjectType());
             relateInfo.setAttachmentProjectSort(ruralProjectRecords.getAttachmentProjectSort());
             //判断是否为打包项目,打包项目无需查看项目送审金额是否为500w以上判定
-            if(0 == projectSort){
+            /*if(0 == projectSort){*/
                 //查看送审金额是否为500w以上金额
                 Integer approvalMoney = projectAccessoryRelationService.decideAttachmentProjectApprovalMoney(projectReportData.getReviewFee());
-                if(1 == approvalMoney){
+                if(0 == approvalMoney){
+                    //金额为0
+                    relateInfo.setAttachmentProjectApprovalMoney(null);
+                }else if(1 == approvalMoney){
                     //500w以下金额状态
                     relateInfo.setAttachmentProjectApprovalMoney("1");
                 }else{
                     //500w以上金额状态
                     relateInfo.setAttachmentProjectApprovalMoney("2");
                 }
-            }else{
+            /*}else{
                 relateInfo.setAttachmentProjectApprovalMoney(null);
-            }
+            }*/
 
             //添加报告类型
             relateInfo.setRequiredStage(1);
@@ -484,7 +487,7 @@ public class RuralCostProjectMessageController extends BaseController {
                 }
 
             }
-        }
+        /*}*/
         //查询总审人员信息
         List<User> auditUserList = userService.getAuditUserList();
         projectcontentinfo1.getProject().setBzshbUserList(auditUserList);

+ 10 - 7
src/main/java/com/jeeplus/modules/ruralprojectrecords/web/RuralProjectMessageController.java

@@ -446,32 +446,35 @@ public class RuralProjectMessageController extends BaseController {
         projectcontent.setProjectReportData(projectReportData);
         //根据条件查询附件必填项
         //判断项目类别是否为打包项目(1:打包项目,0:非打包项目)
-        Integer projectSort = projectAccessoryRelationService.decideAttachmentProjectSort(ruralProjectRecords.getAttachmentProjectSort());
+        /*Integer projectSort = projectAccessoryRelationService.decideAttachmentProjectSort(ruralProjectRecords.getAttachmentProjectSort());
 
         Boolean flag = false;
         //如果是打包项目或者报告送审价不为null则可进行查询附件类型
         if(1 == projectSort || null != projectReportData.getReviewFee()){
             flag = true;
         }
-        if(flag) {
+        if(flag) {*/
             ProjectAccessoryRelationInfo relateInfo = new ProjectAccessoryRelationInfo();
             //添加项目类型
             relateInfo.setAttachmentProjectType(ruralProjectRecords.getProjectType());
             relateInfo.setAttachmentProjectSort(ruralProjectRecords.getAttachmentProjectSort());
             //判断是否为打包项目,打包项目无需查看项目送审金额是否为500w以上判定
-            if(0 == projectSort){
+            /*if(0 == projectSort){*/
                 //查看送审金额是否为500w以上金额
                 Integer approvalMoney = projectAccessoryRelationService.decideAttachmentProjectApprovalMoney(projectReportData.getReviewFee());
-                if(1 == approvalMoney){
+                if(0 == approvalMoney){
+                    //金额为0
+                    relateInfo.setAttachmentProjectApprovalMoney(null);
+                }else if(1 == approvalMoney){
                     //500w以下金额状态
                     relateInfo.setAttachmentProjectApprovalMoney("1");
                 }else{
                     //500w以上金额状态
                     relateInfo.setAttachmentProjectApprovalMoney("2");
                 }
-            }else{
+            /*}else{
                 relateInfo.setAttachmentProjectApprovalMoney(null);
-            }
+            }*/
 
             //添加报告类型
             relateInfo.setRequiredStage(1);
@@ -493,7 +496,7 @@ public class RuralProjectMessageController extends BaseController {
                 }
 
             }
-        }
+        /*}*/
 
         //查询总审人员信息
         List<User> auditUserList = userService.getAuditUserList();

+ 21 - 0
src/main/java/com/jeeplus/modules/ruralprojectrecords/web/RuralProjectRecordsController.java

@@ -3,6 +3,8 @@
  */
 package com.jeeplus.modules.ruralprojectrecords.web;
 
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
 import com.google.common.collect.Lists;
 import com.jeeplus.common.config.Global;
 import com.jeeplus.common.oss.OSSClientUtil;
@@ -51,6 +53,7 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.File;
 import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.util.*;
@@ -378,6 +381,24 @@ public class RuralProjectRecordsController extends BaseController {
 		addMessage(redirectAttributes, "删除项目成功");
 		return "redirect:"+Global.getAdminPath()+"/ruralProject/ruralProjectRecords/?repage";
 	}
+
+	/**
+	 * 项目相应文件批量下载并压缩
+	 */
+	@RequiresPermissions("ruralProject:ruralProjectRecords:del")
+	@RequestMapping(value = "exportAll")
+	public String exportAll(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
+		String listIds = request.getParameter("listId");
+		List<String> idList = Arrays.asList(listIds.split(","));
+		try {
+			String filePath = projectRecordsService.exportAll(idList);
+			projectRecordsService.downloadZipFile(filePath,response);
+			return null;
+		} catch (Exception e) {
+			addMessage(redirectAttributes, "批量下载项目文件失败!");
+		}
+		return "redirect:"+Global.getAdminPath()+"/ruralProject/ruralProjectRecords/?repage";
+	}
 	
 	/**
 	 * 导出excel文件

+ 102 - 0
src/main/java/com/jeeplus/modules/utils/SftpClientUtil.java

@@ -1,12 +1,15 @@
 package com.jeeplus.modules.utils;
 
 import java.io.*;
+import java.net.URLDecoder;
 import java.net.URLEncoder;
 import java.util.*;
 
 import com.jcraft.jsch.*;
+import com.jeeplus.common.bos.BOSClientUtil;
 import com.jeeplus.common.config.Global;
 import com.jeeplus.common.utils.StringUtils;
+import org.apache.commons.fileupload.util.Streams;
 import org.apache.log4j.Logger;
 import org.springframework.mock.web.MockMultipartFile;
 import org.springframework.web.multipart.MultipartFile;
@@ -31,6 +34,8 @@ public class SftpClientUtil {
     private final static String password = Global.getConfig("remoteServer.password");
     /** 目录 */
     private final static String directory = Global.getConfig("remoteServer.directory");
+    /** 文件存储方式(0:本地服务器存储。1:云端存储) */
+    private final static String uploadMode = Global.getConfig("remoteServer.uploadMode");
 
 
     /**
@@ -298,6 +303,103 @@ public class SftpClientUtil {
         return null;
     }
 
+    /**
+     * 下载文件
+     *
+     * @param directory     SFTP服务器的文件路径
+     * @param downloadFile  SFTP服务器上的文件名
+     * @return              字节数组
+     */
+    public byte[] downloadRuralProject(String directory, String downloadFile,String downLoadFilePath,String finalFileName) throws IOException {
+        File dirFile = new File(downLoadFilePath);
+        if (!dirFile.exists()) {
+            dirFile.mkdirs();
+        }
+        if("1".equals(uploadMode)){
+            OutputStream out = null;
+            InputStream in = null;
+            FileOutputStream fileOut = null;
+            String fileNamePath = directory +"/" + downloadFile;
+            try {
+                fileNamePath = URLDecoder.decode(fileNamePath,"UTF-8");
+                String path = fileNamePath.substring(fileNamePath.indexOf(".com") + 4, fileNamePath.length());
+                String fileName = URLEncoder.encode(fileNamePath.substring(fileNamePath.lastIndexOf("/") + 1, fileNamePath.length()),"UTF-8");
+                BOSClientUtil bosClientUtil = new BOSClientUtil();
+                in = bosClientUtil.getObject(path);
+
+                BufferedInputStream bis = new BufferedInputStream(in);
+                //判断文件的保存路径后面是否以/结尾
+                if (!downLoadFilePath.endsWith("/")) {
+                    downLoadFilePath += "/";
+                }
+                //写入到文件(注意文件保存路径的后面一定要加上文件的名称)
+                fileOut = new FileOutputStream(downLoadFilePath + downloadFile);
+                BufferedOutputStream bos = new BufferedOutputStream(fileOut);
+                byte[] buf = new byte[4096];
+                int length = bis.read(buf);
+                //保存文件
+                while(length != -1)
+                {
+                    bos.write(buf, 0, length);
+                    length = bis.read(buf);
+                }
+                bos.close();
+                fileOut.close();
+            }catch (IOException e){
+                e.printStackTrace();
+            }finally {
+                if (out != null) {
+                    out.close();
+                }
+                if (in != null) {
+                    in.close();
+                }
+            }
+        }else{
+            try{
+                String path = directory.substring(directory.indexOf("=")+1, directory.length());
+                if(StringUtils.isNotBlank(host) && ("127.0.0.1".equals(host) || "localhost".equals(host))){
+                    String wPath = path+"/"+downloadFile;
+                    File fileurl = new File(wPath);
+                    //将文件读入文件流
+                    InputStream inStream = new FileInputStream(fileurl);
+
+                    File file = new File(downLoadFilePath,finalFileName);
+                    //将下载保存到文件。
+                    FileOutputStream out = new FileOutputStream(file);
+                    Streams.copy(inStream, out, true);
+                }else{
+                    ChannelSftp sftp = connect();
+                    if(path != null && !"".equals(path)){
+                        sftp.cd(path);
+                    }
+                    InputStream inputStream = sftp.get(downloadFile);
+
+                    BufferedInputStream bis = new BufferedInputStream(inputStream);
+                    //写入到文件(注意文件保存路径的后面一定要加上文件的名称)
+                    FileOutputStream  fileOut = new FileOutputStream(downLoadFilePath + "/" + finalFileName);
+                    BufferedOutputStream bos = new BufferedOutputStream(fileOut);
+
+                    byte[] buf = new byte[4096];
+                    int length = bis.read(buf);
+                    //保存文件
+                    while(length != -1)
+                    {
+                        bos.write(buf, 0, length);
+                        length = bis.read(buf);
+                    }
+                    bos.close();
+                    bis.close();
+                }
+            }catch (SftpException | IOException e){
+                logger.error("文件下载异常!", e);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        return null;
+    }
+
 
     /**
      * File转MultipartFile

+ 198 - 0
src/main/java/com/jeeplus/modules/utils/ZipCompressUtil.java

@@ -0,0 +1,198 @@
+package com.jeeplus.modules.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.tools.zip.ZipEntry;
+import org.apache.tools.zip.ZipOutputStream;
+/**
+ *
+ * 文件压缩成zip
+ *
+ */
+public class ZipCompressUtil {
+
+    /**
+     *
+     * 将文件夹及文件夹包含的内容压缩成zip文件
+     * (为了解决中文乱码的问题,ZipOutputStream用org.apache.tools.zip.*)
+     *
+     * @param inputFile 源文件
+     * @param delFlag 删除源文件标记
+     * @return File 压缩后的文件
+     */
+    public File zipCompress(File inputFile, boolean delFlag) throws Exception{
+        File zipFile = null;
+        //创建zip输出流
+        //为了解决中文乱码的问题,ZipOutputStream用org.apache.tools.zip.*
+        //不要用 java.util.zip.*
+        ZipOutputStream zos = null;
+        if(inputFile != null && inputFile.exists()) {
+            try {
+                String path = inputFile.getCanonicalPath();
+                String zipFileName = path + ".zip";
+                zipFile = new File(zipFileName);
+                if(zipFile.exists()) {
+                    zipFile.delete();
+                }
+                zipFile.createNewFile();//创建文件
+                zos = new ZipOutputStream(new FileOutputStream(zipFile));
+                //解决中文乱码问题,指定编码GBK
+                zos.setEncoding("GBK");
+                //压缩文件或文件夹
+                this.compressFile(zos, inputFile, inputFile.getName());
+            }catch(Exception e) {
+                System.out.println("文件压缩异常:" + e);
+                throw e;
+            }finally {
+                try {
+                    if(zos != null) {
+                        //先调用outputStream的flush()再关闭流;
+                        //流如果未正常关闭,则会在解压的时候出现压缩文件损坏的现象
+                        zos.flush();
+                        zos.close();
+                    }
+
+                    if(delFlag) {
+                        //递归删除源文件及源文件夹
+                        this.deleteFile(inputFile);
+                    }
+                }catch(Exception ex) {
+                    System.out.println("输出流关闭异常:" + ex);
+                }
+            }
+        }
+
+        return zipFile;
+    }
+
+    /**
+     * 压缩文件或文件夹
+     * (ZipEntry 使用org.apache.tools.zip.*,不要用 java.util.zip.*)
+     *
+     * @param zos zip输出流
+     * @param sourceFile 源文件
+     * @param baseName 父路径
+     * @throws Exception 异常
+     */
+    private void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws Exception{
+        if(!sourceFile.exists()) {
+            return;
+        }
+
+        //若路径为目录(文件夹)
+        if(sourceFile.isDirectory()) {
+            //取出文件夹中的文件(或子文件夹)
+            File[] fileList = sourceFile.listFiles();
+            //若文件夹为空,则创建一个目录进入点
+            if(fileList.length == 0) {
+                //文件名称后跟File.separator表示这是一个文件夹
+                zos.putNextEntry(new ZipEntry(baseName + File.separator));
+                //若文件夹非空,则递归调用compressFile,对文件夹中的每个文件或每个文件夹进行压缩
+            }else {
+                for(int i = 0; i < fileList.length; i++) {
+                    this.compressFile(zos, fileList[i],
+                            baseName + File.separator + fileList[i].getName());
+                }
+            }
+
+            //若为文件,则先创建目录进入点,再将文件写入zip文件中
+        }else {
+            ZipEntry ze = new ZipEntry(baseName);
+            //设置ZipEntry的最后修改时间为源文件的最后修改时间
+            ze.setTime(sourceFile.lastModified());
+            zos.putNextEntry(ze);
+
+            FileInputStream fis = new FileInputStream(sourceFile);
+            this.copyStream(fis, zos);
+            try {
+                if(fis != null) {
+                    fis.close();
+                }
+            }catch(Exception e) {
+                System.out.println("输入流关闭异常:" + e);
+            }
+        }
+    }
+
+    /**
+     * 流拷贝
+     *
+     * @param in 输入流
+     * @param out 输出流
+     * @throws IOException
+     */
+    private void copyStream(InputStream in, OutputStream out) throws IOException{
+        int bufferLength = 1024 * 100;
+        synchronized(in) {
+            synchronized(out) {
+                int count = 0;
+                byte[] buffer = new byte[bufferLength];
+                while((count = in.read(buffer, 0, bufferLength)) != -1) {
+                    out.write(buffer, 0, count);
+                }
+                out.flush();
+            }
+        }
+    }
+
+    /**
+     * 递归删除文件夹中的目录及文件
+     *
+     * @param sourceFile
+     * @throws Exception
+     */
+    private void deleteFile(File sourceFile) throws Exception{
+        //如果路径为目录
+        if(sourceFile.isDirectory()) {
+            //取出文件夹中的文件或子文件夹
+            File[] fList = sourceFile.listFiles();
+            if(fList.length == 0) {
+                sourceFile.delete();
+            }else {
+                for(int i = 0; i < fList.length; i++) {
+                    this.deleteFile(fList[i]);
+                }
+                sourceFile.delete();
+            }
+            //如果为文件则直接删除
+        }else {
+            sourceFile.delete();
+        }
+    }
+
+    /**
+     *     当前路径下若已有同名文件又不愿意覆盖,
+     *     则依次追加后缀
+     *
+     * @param path
+     * @param docName
+     * @return
+     * @throws Exception
+     */
+    private File createFile(String path, final String docName) throws Exception{
+        //创建目标文件
+        File destFile = new File(path, docName);
+        //如果路径下存在同名文件又不愿意覆盖,
+        //那么则依次给文件加后缀(2)、(3)……
+        if(destFile.exists()) {
+            int i = 1;
+            do {
+                ++i;
+                //按“.”分割
+                String[] doc = docName.split("\\.");
+                destFile = new File(path, doc[0] + "(" + i + ")" + "." + doc[1]);
+
+                //直到文件创建成功则跳出循环
+            }while(!destFile.createNewFile());
+        }else {
+            destFile.createNewFile();
+        }
+        return destFile;
+    }
+}
+

+ 22 - 1
src/main/webapp/webpage/modules/ruralprojectrecords/cost/ruralCostProjectRecordsList.jsp

@@ -258,6 +258,9 @@
 					<shiro:hasPermission name="ruralProject:ruralCostProjectRecords:export">
 						<table:exportExcel url="${ctx}/ruralProject/ruralCostProjectRecords/export"></table:exportExcel><!-- 导出按钮 -->
 					</shiro:hasPermission>
+					<shiro:hasPermission name="ruralProject:ruralCostProjectRecords:exportAll">
+						<button type="button" data-toggle="tooltip" data-placement="top" class="nav-btn nav-btn-delete" id="delUser"><i class="fa fa-file-excel-o"> 批量下载</i></button>
+					</shiro:hasPermission>
 					<button class="nav-btn nav-btn-refresh" data-toggle="tooltip" data-placement="left" onclick="sortOrRefresh()" title="刷新"><i class="glyphicon glyphicon-repeat"></i>&nbsp;刷新</button>
 					<div style="clear: both;"></div>
 				</div>
@@ -278,10 +281,11 @@
     layui.use('table', function(){
         layui.table.render({
             limit:${ page.pageSize }
+			,id:"checkboxTable"
             ,elem: '#contentTable1'
             ,page: false
             ,cols: [[
-                // {checkbox: true, fixed: true},
+				{checkbox: true, fixed: true},
                 {field:'index',align:'center', title: '序号',width:40}
                 ,{field:'projName',align:'center', title: '项目名称',minWidth:200,templet:function(d){
                         return "<a class=\"attention-info\" title=\"" + d.projName + "\" href=\"javascript:void(0);\" onclick=\"openDialogView('查看项目', '${ctx}/ruralProject/ruralCostProjectRecords/view?id=" + d.id +"','95%', '95%')\">" + d.projName + "</a>";
@@ -386,6 +390,23 @@
             // ,even: true
             // ,height: 315
         });
+		$("#delUser").bind("click",function () {
+			//获得表格CheckBox已经选中的行的信息
+			var checkList = layui.table.checkStatus('checkboxTable').data;
+			//定义数组存放批量删除的行的id
+			var listId = [];
+			//进行遍历所有选中行数据,拿出每一行的id存储到数组中
+			$.each(checkList, function (i, data) {
+				listId.push(data.id);
+			});
+			if (listId.length <= 0) {
+				layer.msg("请选择需要下载的项目信息", {icon: 2})
+			} else {
+				$("#searchForm").attr("action","${ctx}/ruralProject/ruralProjectRecords/exportAll?listId="+ listId);
+				$("#searchForm").submit();
+				return true;
+			}
+		});
     })
 
     resizeListTable();

+ 21 - 3
src/main/webapp/webpage/modules/ruralprojectrecords/ruralProjectRecordsList.jsp

@@ -280,12 +280,12 @@
 					<shiro:hasPermission name="ruralProject:ruralProjectRecords:add">
 						<table:addRow url="${ctx}/ruralProject/ruralProjectRecords/form" title="项目"></table:addRow><!-- 增加按钮 -->
 					</shiro:hasPermission>
-					<shiro:hasPermission name="ruralProject:ruralProjectRecords:del">
-						<%--<table:delRow url="${ctx}/project/projectRecords/deleteAll" id="contentTable"></table:delRow><!-- 删除按钮 -->--%>
-					</shiro:hasPermission>
 					<shiro:hasPermission name="ruralProject:ruralProjectRecords:export">
 						<table:exportExcel url="${ctx}/ruralProject/ruralProjectRecords/export"></table:exportExcel><!-- 导出按钮 -->
 					</shiro:hasPermission>
+					<shiro:hasPermission name="ruralProject:ruralProjectRecords:exportAll">
+						<button type="button" data-toggle="tooltip" data-placement="top" class="nav-btn nav-btn-delete" id="delUser"><i class="fa fa-file-excel-o"> 批量下载</i></button>
+					</shiro:hasPermission>
 					<button class="nav-btn nav-btn-refresh" data-toggle="tooltip" data-placement="left" onclick="sortOrRefresh()" title="刷新"><i class="glyphicon glyphicon-repeat"></i>&nbsp;刷新</button>
 					<div style="clear: both;"></div>
 				</div>
@@ -306,6 +306,7 @@
     layui.use('table', function(){
         layui.table.render({
             limit:${ page.pageSize }
+			,id:"checkboxTable"
             ,elem: '#contentTable1'
             ,page: false
             ,cols: [[
@@ -417,6 +418,23 @@
             // ,even: true
             // ,height: 315
         });
+		$("#delUser").bind("click",function () {
+			//获得表格CheckBox已经选中的行的信息
+			var checkList = layui.table.checkStatus('checkboxTable').data;
+			//定义数组存放批量删除的行的id
+			var listId = [];
+			//进行遍历所有选中行数据,拿出每一行的id存储到数组中
+			$.each(checkList, function (i, data) {
+				listId.push(data.id);
+			});
+			if (listId.length <= 0) {
+				layer.msg("请选择需要下载的项目信息", {icon: 2})
+			} else {
+				$("#searchForm").attr("action","${ctx}/ruralProject/ruralProjectRecords/exportAll?listId="+ listId);
+				$("#searchForm").submit();
+				return true;
+			}
+		});
     })
 
     resizeListTable();