`
huangyongxing310
  • 浏览: 494142 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

文件上传下载

 
阅读更多
1.文件ID,名字(源,目标),大小,路径(/aa/bb/s.jpg),访问是否需要令牌
2.图片压缩在前端进行(接收base64)
3.保存文件时要用sessonID(或者后端的令牌)










@Action(value = "commonFileSave", results = { @Result(name = "success", type = "stream", params = { "contentType",
			"text/html", "inputName", "ajaxOutData" }) })
	public String commonFileSave() throws Exception {
		try {
			service.commonFileSave(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	@Action(value = "commonFileDel", results = { @Result(name = "success", type = "stream", params = { "contentType",
			"text/html", "inputName", "ajaxOutData" }) })
	public String commonFileDel() throws Exception {
		try {
			service.commonFileDel(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	@Action(value = "commonFileDown", results = { @Result(name = "success", type = "stream", params = { "contentType",
			"application/octet-stream", "inputName", "downAttachStream", "contentDisposition",
			"attachment;filename=\"${downAttachFileName}\"", "bufferSize", "4096" }) })
	public String commonFileDown() throws Exception {
		try {
			service.commonFileDown(this);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";

	}

//	@Action(value = "commonFilesDown", results = { @Result(name = "success", type = "stream", params = { "contentType",
//			"application/octet-stream", "inputName", "downAttachStream", "contentDisposition",
//			"attachment;filename=\"${downAttachFileName}\"", "bufferSize", "4096" }) })
//	public String commonFilesDown() throws Exception {
//		try {
//			service.commonFilesDown(this);
//			return "success";
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return "success";
//	}
	
	@Action(value = "commonFileInfoList", results = { @Result(name = "success", type = "stream", params = { "contentType",
			"text/html", "inputName", "ajaxOutData" }) })
	public String commonFileInfoList() throws Exception {
		try {
			service.commonFileInfoList(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}






public class CommonFileListServiceImpl {

	private ManageServ manageServ;

	@Autowired
	private FTPService ftpService;

	@Autowired
	AttachInfoService attachInfoService;

	@Resource(name = "htwy_ManageServ")
	public void setManageServ(ManageServ serv) {
		this.manageServ = serv;
	}

	public void commonFileDel(CommonFileListAction action) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			
			String dbKey = CommonManage.toNotNullString(VueParamUtils.getParam("dbKey"));
//			String busField = CommonManage.toNotNullString(VueParamUtils.getParam("busField")); //matMakeReport,store
//			String busType = CommonManage.toNotNullString(VueParamUtils.getParam("busType"));  //supermarket
//			String busKey = CommonManage.toNotNullString(VueParamUtils.getParam("busKey"));
//			String describe = CommonManage.toNotNullString(VueParamUtils.getParam("describe"));
			String id = CommonManage.toNotNullString(VueParamUtils.getParam("id"));
			
			if ("".equals(dbKey)) {
				throw new RuntimeException("dbKey为空");
			}

//			if ("".equals(id)) {
//				throw new RuntimeException("busField为空");
//			}

			if ("".equals(id)) { //为空直接返回成功
				result.put("flag", true);
				action.setAjaxOutData(new ByteArrayInputStream(Json.Encode(result).toString().getBytes("utf-8")));
				return;
			}
			
			String ids = id;
//			ids = ids.replaceAll("'", "");
			if (!CommonManage.notNull(ids)) {
				throw new RuntimeException("附件Id为空");
			}

			String idarr[] = ids.split(",");

			System.out.println("StoreSalesValueServiceImpl commonFileDel idarr == " + JSON.toJSONString(idarr));

			attachInfoService.delAttachByIds(dbKey, idarr);

			result.put("flag", true);
			action.setAjaxOutData(new ByteArrayInputStream(Json.Encode(result).toString().getBytes("utf-8")));
			return;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("flag", false);
			result.put("msg", e.getMessage());
			action.setAjaxOutData(new ByteArrayInputStream(Json.Encode(result).toString().getBytes("utf-8")));
			return;
		}

	}

	public void commonFileDown(CommonFileListAction action) throws Exception {
		String dbKey = CommonManage.toNotNullString(VueParamUtils.getParam("dbKey"));
//		String busField = CommonManage.toNotNullString(VueParamUtils.getParam("busField")); //matMakeReport,store
//		String busType = CommonManage.toNotNullString(VueParamUtils.getParam("busType"));  //supermarket
//		String busKey = CommonManage.toNotNullString(VueParamUtils.getParam("busKey"));
//		String describe = CommonManage.toNotNullString(VueParamUtils.getParam("describe"));
		String id = CommonManage.toNotNullString(VueParamUtils.getParam("id"));
		
		if ("".equals(dbKey)) {
			throw new RuntimeException("dbKey为空");
		}

//		if ("".equals(id)) {
//			throw new RuntimeException("busField为空");
//		}

		if ("".equals(id)) {
			throw new RuntimeException("附件Id为空");
		}


		CommonServ serv = getCommonServByKey(dbKey);
		AttachInfo AttachInfo = serv.findByPid1(AttachInfo.class, id);

		if (AttachInfo == null) {
			throw new RuntimeException(id + "的数据信息不存在");
		}

		String DownAttachFileName = AttachInfo.getFileName();

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();

		attachInfoService.downloadById(dbKey, id, outStream);

		action.setDownAttachStream(new ByteArrayInputStream(outStream.toByteArray()));
		// url转码时会把空格转成加号,替换回来
		action.setDownAttachFileName(URLEncoder.encode(DownAttachFileName, "UTF-8").replaceAll("\\+", "%20"));

	}

//	public void commonFilesDown(CommonFileListAction action) throws Exception {
//		ZipOutputStream zipOutputStream = null;
//		File zipFile = null;
//
//		try {
//			String pks = action.getIds();
//
////			String pk = action.getId();
//
//			String dbKey = CommonManage.toNotNullString(action.getDbKey());
////		String busField = CommonManage.toNotNullString(action.getBusField());
////		String busType = CommonManage.toNotNullString(action.getBusType());
////		String busKey = CommonManage.toNotNullString(action.getBusKey());
////		String describe = CommonManage.toNotNullString(action.getDescribe());
//
//			if ("".equals(dbKey)) {
//				throw new RuntimeException("dbKey为空");
//			}
//
//			String ids[] = pks.split(",");
//
//			if (ids == null || ids.length == 0) {
//				throw new RuntimeException(pks + "为空");
//			}
//
//			CommonServ serv = getCommonServByKey(action.getDbKey());
//
//			HttpServletRequest request = CommonManage.getRequest();
//			String uuid = StringUtils.getUUID();
//			String path = request.getSession().getServletContext().getRealPath("/");
//			String zipFileName = uuid + ".zip";
//
//			String zipPath = path + "userfiles/uploadFile/" + zipFileName;// 避免重复下载时读取旧文件
//
//			zipFile = new File(zipPath); //
//
//			zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
//
//			for (String pk : ids) {
//				AttachInfo AttachInfo = serv.findByPid1(AttachInfo.class, pk);
//				if (AttachInfo == null) {
//					throw new RuntimeException(pk + "的数据信息不存在");
//				}
//
//				String DownAttachFileName = AttachInfo.getFileName();
//
//				ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//
//				attachInfoService.downloadById(dbKey, pk, outStream);
//
////			String path2 = path + "userfiles/uploadFile/" + DownAttachFileName;
//
//				ZipEntry entry = new ZipEntry(DownAttachFileName);
//				zipOutputStream.putNextEntry(entry);
//				zipOutputStream.write(outStream.toByteArray(), 0, outStream.toByteArray().length);
//
//				zipOutputStream.closeEntry();
//
//			}
//
//			zipOutputStream.close();// 记得关闭资源
//
//			FileInputStream in = new FileInputStream(new File(zipPath));
////		FileInputStream fis=new FileInputStream("test");  
//			BufferedInputStream bis = new BufferedInputStream(in);
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			byte[] buffer = new byte[1024 * 8];
//			int n = -1;
//			while ((n = in.read(buffer)) != -1) {
//				baos.write(buffer, 0, n);
//			}
//
//			if (bis != null) {
//				bis.close();
//			}
//
//			if (in != null) {
//				in.close();
//			}
//
//			action.setDownAttachStream(new ByteArrayInputStream(baos.toByteArray()));
//			// url转码时会把空格转成加号,替换回来
//			action.setDownAttachFileName(URLEncoder.encode(zipFileName, "UTF-8").replaceAll("\\+", "%20"));
//
//			boolean boo = zipFile.delete();
//			System.out.println(boo ? path + zipFileName + "文件已删除" : zipFileName + "文件未删除");
//		} catch (Exception e) {
//			e.printStackTrace();
//
//			if (zipOutputStream != null) {
//				zipOutputStream.close();
//			}
//			if (zipFile != null) {
//				boolean boo = zipFile.delete();
//				System.out.println(boo ? "文件已删除(异常)" :  "文件未删除(异常)");
//			}
//
//		}
//
//	}

	public void commonFileSave(CommonFileListAction action) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String dbKey = CommonManage.toNotNullString(VueParamUtils.getParam("dbKey"));
			String busField = CommonManage.toNotNullString(VueParamUtils.getParam("busField")); //matMakeReport,store
			String busType = CommonManage.toNotNullString(VueParamUtils.getParam("busType"));  //supermarket
			String busKey = CommonManage.toNotNullString(VueParamUtils.getParam("busKey"));
			String describe = CommonManage.toNotNullString(VueParamUtils.getParam("describe"));
//			String id = CommonManage.toNotNullString(VueParamUtils.getParam("id"));
			
			if ("".equals(dbKey)) {
				throw new RuntimeException("dbKey为空");
			}

			if ("".equals(busField)) {
				throw new RuntimeException("busField为空");
			}
			
			
//			if ("".equals(busType)) {
//				throw new RuntimeException("busType为空");
//			}

			if ("".equals(busKey)) {
				throw new RuntimeException("busKey为空");
			}
			
			String imageInfoListString = CommonManage.toNotNullString(VueParamUtils.getParam("imageInfoList"));
			
			if(imageInfoListString.length()>2) {
				fileSave( dbKey, busField, busType, busKey, describe, imageInfoListString);
			}
			
			
			
			

//			List<ImageInfo> imageInfoList = JSON.parseArray(imageInfoListString, ImageInfo.class);
//
//			if (imageInfoList == null || imageInfoList.size() == 0) {
//				ExceptionUtils.throwRuntimeException("上传图片不能为空");
//			}
			
			
//			//===============
//			int imageHave = 0;
//			for (ImageInfo imageInfo : imageInfoList) {
//				//// 文件状态,delete,update,add
//				String fileFlag = imageInfo.getFileFlag().trim();
//
//				if (fileFlag.equals("delete")) {
//				}
//				if (fileFlag.equals("update")) {
//					imageHave = 1;
//				}
//
//				if (fileFlag.equals("add")) {
//					imageHave = 1;
//				}
//			}
//			if (imageHave == 0) {
//				ExceptionUtils.throwRuntimeException("上传图片不能为空");
//			}
//
//			//===============
//			if (imageInfoList != null && imageInfoList.size() > 0) {
//				for (ImageInfo imageInfo : imageInfoList) {
//					String fileId = imageInfo.getFileId().trim();
//					if (fileId.equals("0") || fileId.equals("")) {
//						fileId = "";
//					}
//
//					//// 文件状态,delete,update,add
//					String fileFlag = imageInfo.getFileFlag().trim();
//					if (fileFlag.equals("delete")) {
//						if (!fileId.equals("")) {
//							String[] imgid = { fileId };
//							attachInfoService.delAttachByIds(dbKey, imgid);
//						}
//					}
//
//					if (fileFlag.equals("update")) {
//
//					}
//
//					if (fileFlag.equals("add")) {
//						String fileData = imageInfo.getFileData();
//						
//						String sfileName = imageInfo.getName().trim();
//						
//						fileData = CommonManage.toNotNullString(fileData, "").replaceAll("data:image/jpeg;base64,", "");
//						
//						
////						System.out.println("fileData = " + fileData);
//						System.out.println("fileData length = " + fileData.length());
//						
//						fileData= fileData.replaceAll(" ", "+");
////						System.out.println("fileData = " + fileData);
//						System.out.println("fileData length = " + fileData.length());
//						
//						
//						String fileName = StringUtils.getUUID() + ".jpg";
//						
////						String fileName = applyId + "_" + elementName + "_" + matTypeName + "_" + StringUtils.getUUID() + ".jpg";
////						String fileName = System.currentTimeMillis()+".jpg";;
//						File file = Base64Utils.base64ToFile(fileData, FileUtil.getRealPathByRelative(FileUtil.getRealRelativePath(fileName)));
//						
//
//						if (null != file && file.length() > 0) {
//							attachInfoService.saveAttach(dbKey,busField, id, busType, fileName, file, "2");
//							file.delete();
//						}
//					}
//				}
//			}

//			Map<String, Object> result = new HashMap<String, Object>();
			
			// 同时返回图像列表数据
						List<Map> fileList = getFileList(dbKey, busField, busType, busKey);

						result.put("fileList", fileList);
			
			// ==============
			action.setAjaxOutData(new ByteArrayInputStream(Json.Encode(ResultUtils.getSuccessResult(result)).toString().getBytes("utf-8")));

		} catch (Exception e) {
			e.printStackTrace();
			action.setAjaxOutData(new ByteArrayInputStream(Json.Encode(ResultUtils.getErrorResult(e)).toString().getBytes("utf-8")));
		}
	}
	
	
	public void commonFileInfoList(CommonFileListAction action) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			
			String dbKey = CommonManage.toNotNullString(VueParamUtils.getParam("dbKey"));
			String busField = CommonManage.toNotNullString(VueParamUtils.getParam("busField")); //matMakeReport,store
			String busType = CommonManage.toNotNullString(VueParamUtils.getParam("busType"));  //supermarket
//			String busKey = CommonManage.toNotNullString(VueParamUtils.getParam("busKey"));
			String describe = CommonManage.toNotNullString(VueParamUtils.getParam("describe"));
			String id = CommonManage.toNotNullString(VueParamUtils.getParam("id"));
			
			if ("".equals(dbKey)) {
				throw new RuntimeException("dbKey为空");
			}

			if ("".equals(busField)) {
				throw new RuntimeException("busField为空");
			}

			if ("".equals(busType)) {
				throw new RuntimeException("busType为空");
			}
			
			if ("".equals(id)) {
				throw new RuntimeException("id为空");
			}
			
			
			
			//------------
			List<Map> fileList = getFileList(dbKey, busField, busType, id);

			result.put("fileList", fileList);
			
			result.put("flag", true);
			action.setAjaxOutData(new ByteArrayInputStream(Json.Encode(result).toString().getBytes("utf-8")));
			return;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("flag", false);
			result.put("msg", e.getMessage());
			action.setAjaxOutData(new ByteArrayInputStream(Json.Encode(result).toString().getBytes("utf-8")));
			return;
		}

	}
	
	
	public void fileSave(String dbKey,String busField,String busType,String busKey,String describe,String imageInfoListString) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			if ("".equals(dbKey)) {
				throw new RuntimeException("dbKey为空");
			}

			if ("".equals(busField)) {
				throw new RuntimeException("busField为空");
			}

//			if ("".equals(busType)) {
//				throw new RuntimeException("busType为空");
//			}
			
			if ("".equals(busKey)) {
				throw new RuntimeException("busKey为空");
			}

			List<ImageInfo> imageInfoList = JSON.parseArray(imageInfoListString, ImageInfo.class);

			if (imageInfoList == null || imageInfoList.size() == 0) {
				ExceptionUtils.throwRuntimeException("上传图片为空");
			}
			
			
			//===============
//			int imageHave = 0;
//			for (ImageInfo imageInfo : imageInfoList) {
//				//// 文件状态,delete,update,add
//				String fileFlag = imageInfo.getFileFlag().trim();
//
//				if (fileFlag.equals("delete")) {
//				}
//				if (fileFlag.equals("update")) {
//					imageHave = 1;
//				}
//
//				if (fileFlag.equals("add")) {
//					imageHave = 1;
//				}
//			}
//			if (imageHave == 0) {
//				ExceptionUtils.throwRuntimeException("上传图片不能为空");
//			}

			//===============
			if (imageInfoList != null && imageInfoList.size() > 0) {
				for (ImageInfo imageInfo : imageInfoList) {
					String fileId = imageInfo.getFileId().trim();
					if (fileId.equals("0") || fileId.equals("")) {
						fileId = "";
					}

					//// 文件状态,delete,update,add
					String fileFlag = imageInfo.getFileFlag().trim();
					if (fileFlag.equals("delete")) {
						if (!fileId.equals("")) {
							String[] imgid = { fileId };
							attachInfoService.delAttachByIds(dbKey, imgid);
						}
					}

					if (fileFlag.equals("update")) {

					}

					if (fileFlag.equals("add")) {
						String fileData = imageInfo.getFileData();
						
						String sfileName = imageInfo.getName().trim();
						
						fileData = CommonManage.toNotNullString(fileData, "").replaceAll("data:image/jpeg;base64,", "");
						
//						System.out.println("fileData = " + fileData);
						System.out.println("fileData length = " + fileData.length());
						
						fileData= fileData.replaceAll(" ", "+");
//						System.out.println("fileData = " + fileData);
						System.out.println("fileData length = " + fileData.length());
						
						
						String fileName = StringUtils.getUUID() + ".jpg";
						
//						String fileName = applyId + "_" + elementName + "_" + matTypeName + "_" + StringUtils.getUUID() + ".jpg";
//						String fileName = System.currentTimeMillis()+".jpg";;
						File file = Base64Utils.base64ToFile(fileData, FileUtil.getRealPathByRelative(FileUtil.getRealRelativePath(fileName)));
						

						if (null != file && file.length() > 0) {
							attachInfoService.saveAttach(dbKey,busField, busKey, busType, fileName, file, "2");
							file.delete();
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	
	public List<Map> getFileList(String dbKey, String busField, String busType, String id) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			if ("".equals(dbKey)) {
				throw new RuntimeException("dbKey为空");
			}

			if ("".equals(busField)) {
				throw new RuntimeException("busField为空");
			}

//			if ("".equals(busType)) {
//				throw new RuntimeException("busType为空");
//			}
			if ("".equals(id)) {
				throw new RuntimeException("id为空");
			}

			// ------------
			List<Map> fileList = new ArrayList<>();
			List<AttachInfo> attachInfos = attachInfoService.getAttachesByBusParams(dbKey, busField, id, busType);
			List<Map> listm = new ArrayList<Map>();
			String[] photoPath = new String[attachInfos.size()];

			if (attachInfos != null && attachInfos.size() > 0) {
//	    		String[] photoPath = new String [attachInfos.size()];
				for (int x = 0; x < attachInfos.size(); x++) {
					AttachInfo attachInfo = attachInfos.get(x);
					String fileName = attachInfo.getFileName();
//
					ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
					attachInfoService.downloadById(dbKey, attachInfo.getId(), byteArrayOutputStream);

//					System.out.println("byteArrayOutputStream = " + byteArrayOutputStream.toString());

					String fileData = Base64Utils.byteArrayOutputStreamToBase64(byteArrayOutputStream);

//					System.out.println("fileData2 = " +  fileData);
					System.out.println("fileData length = " + fileData.length());

					fileData = "data:image/jpeg;base64," + fileData;

//					System.out.println("fileData = " + fileData.toString());
//
					Map map2 = new HashMap<>();
					map2.put("name", attachInfo.getFileName());
					map2.put("size", attachInfo.getSize() + "");
					map2.put("fileId", attachInfo.getId());
					map2.put("fileFlag", "update");
					map2.put("fileData", fileData);

					fileList.add(map2);
				}
			}

			return fileList;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}


	/**
	 * 通过数据库键值,获取service
	 */
	public CommonServ getCommonServByKey(String dbKey) throws Exception {
		Assert.notNull(dbKey, "dbKey参数不能为空,请检查");
		return (CommonServ) manageServ.getClass().getMethod("getCommonServ" + dbKey, new Class[] {}).invoke(manageServ,
				new Object[] {});
	}


}











package com.haday.springbootplus.supermarketSys.fileUpload.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.haday.springbootplus.common.vo.Paging;
import com.haday.springbootplus.manage.service.ManageServ;
import com.haday.springbootplus.manage.service.impl.LoadDataServiceImpl;
import com.haday.springbootplus.supermarketSys.attach.service.FileInfoService;
import com.haday.springbootplus.supermarketSys.fileUpload.param.DeleteFileParam;
import com.haday.springbootplus.supermarketSys.fileUpload.param.FileUploadParam;
import com.haday.springbootplus.supermarketSys.fileUpload.param.GetFileListParam;
import com.haday.springbootplus.supermarketSys.fileUpload.param.GetFilesParam;
import com.haday.springbootplus.util.BaseScanSqlCommand;
import com.haday.springbootplus.util.ExceptionUtils;
import com.haday.springbootplus.util.FileUtils;
import com.haday.springbootplus.util.ListUtils;
import com.haday.springbootplus.util.LogUtils;
import com.haday.springbootplus.util.ObjectValidityUtils;
import com.haday.springbootplus.util.ResultUtils;
import com.haday.springbootplus.util.StringUtils;
import com.haday.springbootplus.util.UUIDUtil;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Api("附件管理")
@RequestMapping("/FileController")
public class FileController {

//	public static final String DBKEY = "1";

	@Autowired
	FileInfoService FileInfoService;

//
//    @Autowired
//    AttachInfoMapper attachInfoMapper;

//	@Autowired
//	FTPService ftpService;

	@Autowired
	private ManageServ manageServ;

	@Autowired
	private LoadDataServiceImpl loadDataServiceImpl;

	@Autowired
	protected HttpServletRequest request; // 这里可以获取到request
	@Autowired
	protected HttpServletResponse response;

//	@PostMapping("/fileUploadTest")
//	@ApiOperation(value = "附件上传", notes = "列表", response = String.class)
//	@ResponseBody
//	public Object fileUploadTest(@RequestParam("file") MultipartFile file) throws Exception {
//		File uploadFile = null;
//		try {
////			 产品目录
//			String busField = request.getParameter("busField");
//			String busKey = request.getParameter("busKey");
//			String busType = request.getParameter("busType");
//			String describe = request.getParameter("describe");
//			String dbKey = request.getParameter("dbKey");
//			String fileName = request.getParameter("fileName");
////			String busField = request.getParameter("busField");
//			LogUtils.info(busField, "uuid");
//
////			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
////			Iterator<String> iter = multiRequest.getFileNames();
//
//////			MultipartFile file = file;
////
//			if (file == null) {
//				ExceptionUtils.throwRuntimeException("上传文件为空");
//			}
//			if (dbKey == null) {
//				ExceptionUtils.throwRuntimeException("上传DbKey为空");
//			}
//			if (busField == null) {
//				ExceptionUtils.throwRuntimeException("上传BusField为空");
//			}
//			if (busType == null) {
//				ExceptionUtils.throwRuntimeException("上传BusType为空");
//			}
//			if (busKey == null) {
//				ExceptionUtils.throwRuntimeException("上传BusKey为空");
//			}
//			if (fileName == null) {
//				ExceptionUtils.throwRuntimeException("上传FileName为空");
//			}
////
////			// ----------------
//			LogUtils.info(file.getOriginalFilename(), "OriginalFilename");
//			fileName = fileName + "_" + UUIDUtil.getUUID() + FileUtils.getExtendName(file.getOriginalFilename());
//			LogUtils.info(fileName, "fileName");
////
////			// ----------------
////
//			uploadFile = new File(fileName); // 创建了一个File对象没有创建文件
//			FileUtil.writeFromStream(file.getInputStream(), uploadFile);
////
//			String storeName = fileName;
//			String uploadPath = StrUtil.concat(true, busField, StrUtil.SLASH, busKey);
//			LogUtils.info(uploadPath, "uploadPath");
////
//			Map<String, String> map = FileInfoService.saveAttach(dbKey, busField, busKey, busType, storeName,
//					uploadFile, uploadPath, describe);
////			// ----------------
//			if (MapUtil.getStr(map, "flag").equalsIgnoreCase("1")) {
//				Object object = ResultUtils.getSuccessResult(map);
//				LogUtils.info(object, "FileUpload return object");
//				return object;
//			} else {
//				Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(map));
////				Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(""));
////				LogUtils.info(object, "FileUpload return object");
//				return object;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			return ResultUtils.getErrorResult(e);
//		} finally {
//			if (uploadFile != null) {
//				// 会在本地产生临时文件,用完后需要删除
//				if (uploadFile.exists()) {
//					FileUtil.del(uploadFile);
//				}
//			}
//		}
//
//	}

	@PostMapping("/fileUpload")
	@ApiOperation(value = "附件上传", notes = "列表", response = String.class)
	@ResponseBody
	public Object fileUpload(@RequestParam("file") MultipartFile file, @RequestParam String busField,
			@RequestParam String busKey, @RequestParam String busType, @RequestParam String describe,
			@RequestParam String dbKey, @RequestParam String fileName) throws Exception {
		File uploadFile = null;
		try {
//			 产品目录
			String uuid = request.getParameter("busField");
			if (file == null) {
				ExceptionUtils.throwRuntimeException("上传文件为空");
			}
			if (dbKey == null) {
				ExceptionUtils.throwRuntimeException("上传DbKey为空");
			}
			if (busField == null) {
				ExceptionUtils.throwRuntimeException("上传BusField为空");
			}
			if (busType == null) {
				ExceptionUtils.throwRuntimeException("上传BusType为空");
			}
			if (busKey == null) {
				ExceptionUtils.throwRuntimeException("上传BusKey为空");
			}
			if (fileName == null) {
				ExceptionUtils.throwRuntimeException("上传FileName为空");
			}

			// ----------------
			String OriginalFilename= file.getOriginalFilename();
			
			describe = StringUtils.toNotNullString(describe) + ",原文件名:" + OriginalFilename;
			
			
			LogUtils.info(file.getOriginalFilename(), "OriginalFilename");
			fileName = fileName + "_" + UUIDUtil.getUUID() + FileUtils.getExtendName(file.getOriginalFilename());
			LogUtils.info(fileName, "fileName");
			//
//						// ----------------
			//
			uploadFile = new File(fileName); // 创建了一个File对象没有创建文件
			FileUtil.writeFromStream(file.getInputStream(), uploadFile);
			//
			String storeName = fileName;
			String uploadPath = StrUtil.concat(true, busField, StrUtil.SLASH, busKey);
			LogUtils.info(uploadPath, "uploadPath");
			//
			Map<String, String> map = FileInfoService.saveAttach(dbKey, busField, busKey, busType, storeName,
					uploadFile, uploadPath, describe);
//						// ----------------
			if (MapUtil.getStr(map, "flag").equalsIgnoreCase("1")) {
				Object object = ResultUtils.getSuccessResult(map);
				LogUtils.info(object, "FileUpload return object");
				return object;
			} else {
				Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(map));
//							Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(""));
//							LogUtils.info(object, "FileUpload return object");
				return object;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.getErrorResult(e);
		} finally {
			if (uploadFile != null) {
				// 会在本地产生临时文件,用完后需要删除
				if (uploadFile.exists()) {
					FileUtil.del(uploadFile);
				}
			}
		}

	}


	@PostMapping("/deleteFile")
	@ApiOperation(value = "附件删除", notes = "附件删除", response = String.class)
	@ResponseBody
	public Object deleteFile(@RequestBody DeleteFileParam param) throws Exception {
		LogUtils.info(param, "deleteFile");
		try {
			if (param.getDbKey() == null) {
				ExceptionUtils.throwRuntimeException("上传DbKey为空");
			}

			List<String> IdList = param.getIdList();

			ObjectValidityUtils.checkNotEmpty(IdList, "删除文件ID");

			String[] ids = new String[IdList.size()];
			for (int i = 0; i < IdList.size(); i++) {
				ids[i] = IdList.get(i);
			}
//			
//			
//			String[] ids = ListUtils.listToArray(IdList);

			boolean flag = FileInfoService.delAttachByIds(param.getDbKey(), ids);

			if (flag) {
				Object object = ResultUtils.getSuccessResult("");
				LogUtils.info(object, "deleteFile return object");
				return object;
			} else {
				Object object = ResultUtils.getResult(false, "附件删除失败,请联系管理员!", JSON.toJSONString(""));
				LogUtils.info(object, "deleteFile return object");
				return object;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.getErrorResult(e);
		} finally {

		}
	}

	@PostMapping("/getFileList")
	@ApiOperation(value = "附件列表", notes = "附件列表", response = String.class)
	@ResponseBody
	public Object getFileList(@RequestBody GetFileListParam param) throws Exception {
		LogUtils.info(param, "getFileList");
		try {
			if (param.getDbKey() == null) {
				ExceptionUtils.throwRuntimeException("上传DbKey为空");
			}

			String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFileList");

			Paging paging = loadDataServiceImpl.getPageData(sql, param.getDbKey(), param.getGetListParam());

			Object object = ResultUtils.getSuccessResult(paging);
			LogUtils.info(object, "getFileList return object");
			return object;

		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.getErrorResult(e);
		} finally {

		}
	}

//	@GetMapping("/getFile/{dbKey}/{id}")
//	@ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
//	@ResponseBody
//	public ResponseEntity<byte[]> getFile(
//			@ApiParam(name = "dbKey", value = "dbKey", required = true) @PathVariable String dbKey,
//			@ApiParam(name = "id", value = "附件id", required = true) @PathVariable String id) throws Exception {
//		LogUtils.info(id, "getFile");
//		try {
//			if (dbKey == null || dbKey.equals("") || dbKey.length() > 2) {
//				ExceptionUtils.throwRuntimeException("DbKey不合规则");
//			}
//
//			if (id == null || id.equals("")) {
//				ExceptionUtils.throwRuntimeException("文件id不合规则");
//			}
//
//			String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFile");
//			sql = sql.replaceAll("##id##", id);
//
//			List<Map<String, Object>> mapList = manageServ.getCommonServ(dbKey).getListMapBySQL(sql);
//
//			if (mapList == null || mapList.size() == 0) {
//				return null;
//			}
//
//			String name = StringUtils.toNotNullString(mapList.get(0).get("file_name"));
//
//			HttpHeaders headers = new HttpHeaders();
//			String fileName = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
//			headers.setContentDispositionFormData("fileName", fileName);
//			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			FileInfoService.downloadById(dbKey, id, baos);
//
//			return new ResponseEntity(baos.toByteArray(), headers, HttpStatus.CREATED);
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		} finally {
//
//		}
//	}

	@GetMapping("/getFile/{dbKey}/{id}")
	@ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
	@ResponseBody
	public void getFile(@ApiParam(name = "dbKey", value = "dbKey", required = true) @PathVariable String dbKey,
			@ApiParam(name = "id", value = "附件id", required = true) @PathVariable String id) throws Exception {
		LogUtils.info(id, "getFile");
		try {
			if (dbKey == null || dbKey.equals("") || dbKey.length() > 2) {
				ExceptionUtils.throwRuntimeException("DbKey不合规则");
			}

			if (id == null || id.equals("")) {
				ExceptionUtils.throwRuntimeException("文件id不合规则");
			}

			String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFile");
			sql = sql.replaceAll("##id##", id);

			List<Map<String, Object>> mapList = manageServ.getCommonServ(dbKey).getListMapObjBySQL(sql);

			if (mapList == null || mapList.size() == 0) {
				ExceptionUtils.throwRuntimeException("id == " + id + ",的文件不存在");
//				response.sendError(500, "id == " + id + ",的文件不存在");
//				return;
			}

			String name = StringUtils.toNotNullString(mapList.get(0).get("file_name"));
			
			String fileOutName = new String(name.getBytes("UTF-8"), "ISO8859-1");
			response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息
			

			FileInfoService.downloadById(dbKey, id, response.getOutputStream());

			response.getOutputStream().flush();
		} catch (Exception e) {
			e.printStackTrace();
			response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionTenLevel(e));// 设置头部信息
			response.sendError(200, "");
		} finally {

		}
	}


	@PostMapping("/getFiles")
	@ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
	@ResponseBody
	public void getFiles(@RequestBody GetFilesParam param) throws Exception {

		LogUtils.info(param, "param");
		ZipOutputStream zipOutputStream = null;
		File zipFile = null;

		BufferedInputStream bis = null;
		BufferedOutputStream out = null;
		FileInputStream in = null;

		try {
			if (param.getDbKey() == null) {
				ExceptionUtils.throwRuntimeException("DbKey为空");
//				response.sendError(500, "DbKey为空");
//				return;
			}

			List<String> IdList = param.getIdList();

			if (IdList == null || IdList.size() == 0) {
				ExceptionUtils.throwRuntimeException("文件ID列表为空");
//				response.sendError(500, "文件ID列表为空");
//				return;
			}
			
			if (IdList.size() >30) {
				ExceptionUtils.throwRuntimeException("文件个数大于30个");
//				response.sendError(500, "文件ID列表为空");
//				return;
			}

			ObjectValidityUtils.checkNotEmpty(IdList, "文件ID列表为空");
			
			String[] ids = new String[IdList.size()];
			
			for(int i= 0 ;i<IdList.size();i++) {
				ids[i] = IdList.get(i);
			}

//			String[] ids = ListUtils.listToArray(IdList);

			// =============
			String uuid = StringUtils.getUUID();
			String zipFileName = uuid + ".zip";

			String path = request.getSession().getServletContext().getRealPath("/");
			LogUtils.info(path, "path");

//			String zipPath = path + "userfiles/uploadFile/" + zipFileName;// 避免重复下载时读取旧文件
			String zipPath = path + zipFileName;// 避免重复下载时读取旧文件

			LogUtils.info(zipPath, "zipPath");

			// ----------
			zipFile = new File(zipPath); //
			zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));

			for (String pk : ids) {
				String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFile");
				sql = sql.replaceAll("##id##", pk);

				List<Map<String, Object>> mapList = manageServ.getCommonServ(param.getDbKey()).getListMapObjBySQL(sql);

				if (mapList == null || mapList.size() == 0) {
					throw new RuntimeException(pk + "的数据信息不存在");
				}

				String DownAttachFileName = StringUtils.toNotNullString(mapList.get(0).get("file_name"));

				ByteArrayOutputStream outStream = new ByteArrayOutputStream();

				FileInfoService.downloadById(param.getDbKey(), pk, outStream);

				// ----------
				ZipEntry entry = new ZipEntry(DownAttachFileName);
				zipOutputStream.putNextEntry(entry);
				zipOutputStream.write(outStream.toByteArray(), 0, outStream.toByteArray().length);

				zipOutputStream.closeEntry();
			}

			zipOutputStream.close();// 记得关闭资源

			in = new FileInputStream(new File(zipPath));
			bis = new BufferedInputStream(in);
			out = new BufferedOutputStream(response.getOutputStream());

//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024 * 128];
			int n = -1;
			while ((n = bis.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}

			out.flush();
			
			

		} catch (Exception e) {
			e.printStackTrace();

//			if (zipOutputStream != null) {
//				zipOutputStream.close();
//			}
			if (zipFile != null) {
				boolean flag = zipFile.delete();
				LogUtils.info(flag, "zipFile delete flag");
				if (flag) {
					LogUtils.info("文件已删除(异常)", "");
				} else {
					LogUtils.info("文件未删除(异常)", "");
				}
			}
//			e.printStackTrace();
			response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionTenLevel(e));// 设置头部信息
			response.sendError(200, "");
		} finally {
			if (bis != null) {
				bis.close();
			}

			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
			
			if (zipOutputStream != null) {
				zipOutputStream.close();
			}
			
			boolean flag = zipFile.delete();
			LogUtils.info(flag, "zipFile delete flag");
			if (flag) {
				LogUtils.info("文件已删除", "");
			} else {
				LogUtils.info("文件未删除", "");
			}
		}
	}

}







package com.haday.springbootplus.supermarketSys.attach.service.impl;

import java.io.File;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.haday.springbootplus.manage.service.ManageServ;
import com.haday.springbootplus.supermarketSys.attach.service.FileInfoService;
import com.haday.springbootplus.supermarketSys.ftp.service.FTPService;
import com.haday.springbootplus.system.entity.UpmsUser;
import com.haday.springbootplus.util.ExceptionUtils;
import com.haday.springbootplus.util.FileUtils;
import com.haday.springbootplus.util.ListUtils;
import com.haday.springbootplus.util.LogUtils;
import com.haday.springbootplus.util.LoginUserInfo;
import com.haday.springbootplus.util.StringUtils;
import com.haday.springbootplus.supermarketSys.attachInfo.entity.AttachInfo;
import com.haday.springbootplus.supermarketSys.attachInfo.service.AttachInfoService;

@Service("fileInfoService")
public class FileInfoServiceImpl implements FileInfoService {

	@Autowired
	private FTPService ftpService;

//	@Autowired
//	private AttachAysncHandler attachAysncHandler;

	@Autowired
	private ManageServ manageServ;

	@Autowired
	private AttachInfoService AttachInfoService;

	@Override
	public Map<String, String> saveAttach(String dbKey, String busField, String busKey, String uploadFileName,
			File file) throws Exception {
		return this.saveAttach(dbKey, busField, busKey, null, uploadFileName, file, null, null);
	}

	@Override
	public Map<String, String> saveAttach(String dbKey, String busField, String busKey, String busType,
			String uploadFileName, File file) throws Exception {
		return this.saveAttach(dbKey, busField, busKey, busType, uploadFileName, file, null, null);
	}

	@Override
	public Map<String, String> saveAttach(String dbKey, String busField, String busKey, String busType,
			String uploadFileName, File file, String uploadPath, String describe) throws Exception {
		Assert.notNull(dbKey, "dbKey不能为空");
		Assert.notNull(file, "待保存文件不能为空");
		Assert.notNull(uploadFileName, "文件名不能为空");

//		String storeName = genRandomFileName(uploadFileName);
		String storeName = uploadFileName;

		if (!this.ftpService.uploadFile(file, uploadPath, storeName)) {
			throw new RuntimeException(MessageFormat.format("上传文件失败 ,路径:{0}", uploadPath));
		}

		// ------------------
		UpmsUser upmsUser = LoginUserInfo.getUserInfo();
		String userId = upmsUser.getUsername();
		String userName = upmsUser.getRealname();

		AttachInfo info = new AttachInfo();

//		AttachInfo info = new AttachInfo();
//
		uploadPath = (uploadPath == null || "".equals(uploadPath)) ? busField : uploadPath;

		if (uploadPath == null) {
			throw new RuntimeException("上传路径不能为空");
		}

		uploadPath = "/".concat(uploadPath).concat("/").concat(storeName);
		
		LogUtils.info(uploadPath, "uploadPath");

		info.setPath(uploadPath);
		info.setFileName(uploadFileName);
		info.setBusKey(busKey);
		info.setBusField(busField);
		info.setBusType(busType == null ? "" : busType);
		info.setDescribe(describe == null ? "" : describe);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String currentTimeStr = format.format(new Date());
		info.setUploadTime(currentTimeStr);
		info.setCreateTime(currentTimeStr);
		info.setSize(file.length());
		info.setUploader(userId);
		info.setUploaderName(userName);
		info.setFtpKey("");
		AttachInfoService.save(info);

		Map<String, String> result = new HashMap<>();
//		if(StringUtils.){
		// 未绑定业务对象id时(新增业务对象时),需要返回附件信息id,供前台处理
		result.put("unattachId", info.getId().toString());
//		}
		result.put("flag", "1");
		return result;
	}

//	@SuppressWarnings("unchecked")
//	private AttachInfo findByIdNoLock(CommonServ serv , String id){
//		String sql = "SELECT * FROM ATTACH_INFO ai WITH(NOLOCK) WHERE ai.id =  ? ";
//		List params = new ArrayList();
//		params.add(id);
//		List<AttachInfo> attaches = serv.getListBySQL(sql , params , AttachInfo.class);
//		if(CollectionUtils.isEmpty(attaches)){
//			return null;
//		}
//		return attaches.get(0);
//	}

//	@Override
//	public Map<String,String> modAttach(String dbKey , String infoId , String fileName, File file , String path , String desc )  {
//		Assert.notNull(infoId,"待修改的附件id不能为空");
//		CommonServ serv = this.getCommonServByKey(dbKey);
//		AttachInfo info = findByIdNoLock(serv, infoId);
//
//		//原附件路径
//		String oldFilePath = info.getPath();
//
//		String storeName = genRandomFileName(fileName);
//		Assert.notNull(file , "待保存文件不能为空");
//		Assert.notNull(fileName , "文件名不能为空");
//		path= (path == null || "".equals(path) ) ? info.getBusField() : path;
//
//		if(!this.ftpService.uploadFile(file,path,storeName)){
//			throw new RuntimeException(MessageFormat.format("上传文件失败 ,路径:{0}", path));
//		}
//
//		path="/".concat(path).concat("/").concat(storeName);
//
//		info.setPath(path);
//		info.setFileName(fileName);
//		info.setFile(file);
//		info.setDescribe(desc == null ? "" : desc);
//		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String currentTimeStr = format.format(new Date());
//		info.setUploadTime(currentTimeStr);
//		info.setSize(file.length());
//		serv.update(info);
//
//		this.ftpService.delFile(oldFilePath);
//
//		Map<String,String> result = new HashMap<>(1);
//		result.put("flag", "1");
//		return result;
//	}

//	@Override
//	public Map<String, String> modAttach(String dbKey , String infoId ,  String fileName ,  File file , String path)  {
//		return this.modAttach(dbKey, infoId, fileName, file, path, null);
//	}

//	@Override
//	public Map<String, String> modAttach(String dbKey, String infoId, String fileName, File file)  {
//		return this.modAttach(dbKey, infoId, fileName, file, null);
//	}

	@Override
	public boolean delAttachByIds(String dbKey, String[] idarr) throws Exception {
		Assert.notEmpty(idarr, "待删除的id集合不能为空");

		if (idarr == null || idarr.length == 0) {
			ExceptionUtils.throwRuntimeException("待删除的id集合不能为空");
		}

		String idIn = ListUtils.ListToSqlInSring(ListUtils.arrayToList(idarr));

		String sql = "SELECT * FROM ATTACH_INFO ai WITH(NOLOCK) WHERE ai.id in (##idIn##)";
		sql = sql.replaceAll("##idIn##", idIn);
		List<Map<String, Object>> mapList = manageServ.getCommonServ(dbKey).getListMapObjBySQL(sql);

		for (Map<String, Object> map : mapList) {
			String path = StringUtils.toNotNullString(map.get("path"));
			if (path.equals("")) {
				continue;
			}

			boolean flag = this.ftpService.delFile(path);
			
			if(!flag) {
//				ExceptionUtils.throwRuntimeException(path + ",删除失败");
				LogUtils.info(flag, "FTP 删除失败");
			}
		}

		String sql2 = "delete FROM  ATTACH_INFO   WHERE id in (##idIn##) ";
		sql2 = sql2.replaceAll("##idIn##", idIn);
		manageServ.getCommonServ(dbKey).executeDeleteBySQL(sql2);

		return true;
	}

//	@Override
//	public BaseResult delAttachByBusParams(String dbKey, String busField, String busKey, String busType)  {
//		List<AttachInfo> attachInfos = this.getAttachesByBusParams(dbKey, busField, busKey, busType);
//		if(!CollectionUtils.isEmpty(attachInfos)){
//			List<String> idarr = new ArrayList<String>();
//			for(AttachInfo info :attachInfos){
//				idarr.add(info.getId());
//			}
//			return this.delAttachByIds(dbKey, idarr.toArray(new String[idarr.size()]));
//		}
//		return BaseResult.SUC;
//	}

//	@SuppressWarnings("unchecked")
//	@Override
//	public List<AttachInfo> getAttachesByBusParams(String dbKey, String busField, String busKey, String busType) {
//		CommonServ serv = this.getCommonServByKey(dbKey);
//		String sql = "SELECT * FROM ATTACH_INFO ai WITH(NOLOCK) WHERE ai.bus_Field = ? AND ai.bus_Key = ? ";
//		if(StringUtil.isBlank(busType)){
//			sql = sql.concat(" AND ISNULL(bus_type,'') = '' ");
//		}else{
//			sql = sql.concat(" AND bus_type = ? ");
//		}
//		sql = sql.replaceFirst("\\?", "'"+busField+"'");
//		sql = sql.replaceFirst("\\?", "'"+busKey+"'");
//		sql = sql.replaceFirst("\\?", "'"+busType+"'");
//
//		List<AttachInfo> attaches = serv.getListBySQL(sql , (List)null ,  AttachInfo.class);
//		return attaches;
//	}

	private static String genRandomFileName(String oriName) {
		String suffix = FileUtils.getExtendName(oriName);
		
		return suffix==null ? StringUtils.getUUID():
			StringUtils.getUUID().concat(".").concat(suffix);
	}
//
//	public static String uuid(){
//		return UUID.randomUUID().toString().replaceAll("-", "");
//	}

	@Override
	public void downloadById(String dbKey, String id, OutputStream outputStream) throws Exception {
//		CommonServ serv = this.getCommonServByKey(dbKey);
//		AttachInfo info = findByIdNoLock(serv, id);

		String sql = "SELECT * FROM ATTACH_INFO ai WITH(NOLOCK) WHERE ai.id = '##id##'";
		sql = sql.replaceAll("##id##", id);
		List<Map<String, Object>> mapList = manageServ.getCommonServ(dbKey).getListMapObjBySQL(sql);

		if (mapList == null || mapList.size() == 0) {
			throw new RuntimeException("id == " + id + ",的附件信息不存在");
		}

		String path = StringUtils.toNotNullString(mapList.get(0).get("path"));
		if (path.equals("")) {
			throw new RuntimeException("id == " + id + ",的附件信息路径不存在");
		}

		if (!ftpService.downloadFile(path, outputStream)) {
			throw new RuntimeException(MessageFormat.format("下载文件失败 ,路径:{0}", path));
		}
	}

//	@Override
//	public void bindBusObj(String dbKey , String unattachIds, String busObjId) {
//		String sql = "UPDATE [dbo].[ATTACH_INFO] SET [bus_key]  = :busKey WHERE [id] in (:ids)" ;
//		Map<String ,Object> params = new HashMap<>();
//		params.put("busKey" , busObjId );
//		String [] idarr = unattachIds.split(",");
//		params.put("ids" , idarr);
//		this.getCommonServByKey(dbKey).executeBySQL(sql , params);
//	}

//	@Override
//	public AttachInfo getAttachById(String dbKey , String id) {
//		return findByIdNoLock(this.getCommonServByKey(dbKey), id);
//	}

//	@Override
//	public AttachInfo save(String dbKey , AttachInfo info) {
//		this.getCommonServByKey(dbKey).save(info);
//		return info;
//	}

//	@Transactional(rollbackFor = Exception.class , isolation = Isolation.READ_UNCOMMITTED)
//	@Override
//	public List<AttachInfo> getAttachByIds(String dbKey , String [] ids ){
//		Assert.notEmpty(ids , "id集合不能为空");
//		CommonServ serv = this.getCommonServByKey(dbKey);
//		Map<String ,Object> params = new HashMap<>();
//		params.put("ids" , ids);
//		String sql = "select * from attach_info a where a.id in (:ids)";
//		List<AttachInfo> infos = serv.getListBySQL(sql, params , AttachInfo.class);
//		return infos ;
//	}

//	@Override
//	public File downloadById(String dbKey, String id) {
//		return this.downloadById(dbKey , id , "");
//	}

//	@Override
//	public File downloadById(String dbKey, String id, String dir) {
//		CommonServ serv = this.getCommonServByKey(dbKey);
//		AttachInfo info = findByIdNoLock(serv, id);
//
//		File folder = new File(FTPService.TMP_DIR , StringUtil.isBlank(dir) ? StringUtil.uuid() : dir);
//		if(!folder.exists()){
//			folder.mkdirs();
//		}
//		File file = new File(folder , info.getFileName());
//		if(file.exists()){
//			return file;
//		}
//		try (FileOutputStream fos = new FileOutputStream(file)){
//			if(!ftpService.downloadFile(info.getPath(), fos)){
//				throw new RuntimeException(MessageFormat.format("下载文件失败 ,路径:{0}", info.getPath()));
//			}
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//		return file;
//	}
}









package com.haday.springbootplus.supermarketSys.ftp.service.impl;
import com.haday.springbootplus.config.FtpConfig;
import com.haday.springbootplus.supermarketSys.ftp.pool.FTPClientConfigure;
import com.haday.springbootplus.supermarketSys.ftp.pool.FTPClientFactory;
import com.haday.springbootplus.supermarketSys.ftp.pool.FTPClientPool;
import com.haday.springbootplus.supermarketSys.ftp.service.FTPService;
import com.haday.springbootplus.util.LogUtils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.*;

/**
 * framework
 *
 * @author yangzj2
 * @date 2017/11/13
 */
@Service
public class FTPServiceImpl implements FTPService {
	
	
	@Autowired
	private  FTPClientConfigure FTPClientConfigure;
	
	@Autowired
	private FTPClientFactory FTPClientFactory;
	
	@Autowired
	private FTPClientPool FTPClientPool;
	
	
	
	
	
	

    /**
     * 获取ftpClient
     * @author caisf
     * @date 2016年6月1日
     * @return
     * @throws Exception
     */
    private FTPClient getFTPClient() throws Exception{
        if(FTPClientConfigure.isPoolEnable()){
//            return FTPClientPool.getInstance().borrowObject();
            return FTPClientPool.borrowObject();
        }else{
//            return FTPClientFactory.getInstance().makeObject();
            return FTPClientFactory.makeObject();
        }
    }

    /**
     * 归还ftpClient
     * @author caisf
     * @date 2016年6月1日
     * @param ftpClient
     * @throws Exception
     */
    private void returnFTPClient(FTPClient ftpClient) throws Exception{
        if(FTPClientConfigure.isPoolEnable()){
//            FTPClientPool.getInstance().returnObject(ftpClient);
            FTPClientPool.returnObject(ftpClient);
        }else{
//            FTPClientFactory.getInstance().destroyObject(ftpClient);
            FTPClientFactory.destroyObject(ftpClient);
        }
    }


    @Override
    public boolean uploadFile(File localFile, String remoteDir) throws Exception {
        return this.uploadFile(localFile, remoteDir, localFile.getName());
    }

    @Override
    public boolean uploadFile(File localFile, String remoteDir, String storeName) throws Exception {
        BufferedInputStream inStream = null;
        boolean success = false;
        FTPClient ftpClient = getFTPClient();
        try {
            if (!mdirs(ftpClient, remoteDir, this.getRoot())) {
//                LogUtils.info(object, objectName);("目录创建失败:" + remoteDir);
//                return false;
            	throw new RuntimeException("目录创建失败:" + remoteDir);
            }
            ftpClient.changeWorkingDirectory(concatPath(this.getRoot(), remoteDir));// 改变工作路径
            inStream = new BufferedInputStream(new FileInputStream(localFile));

            success = ftpClient.storeFile(storeName, inStream);
            if (success == true) {
                LogUtils.info(localFile.getName() + "上传成功","");
                return success;
            }
        } catch (FileNotFoundException e) {
//            SysLog.log(localFile + "未找到");
            throw new RuntimeException(localFile + "未找到");
        } catch (IOException e) {
//            SysLog.log(e);
            throw e;
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                returnFTPClient(ftpClient);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return success;
    }

    @Override
    public boolean downloadFile(String remoteDir, String remoteFileName, String localDir) {
        String strFilePath = concatPath(localDir, remoteFileName);
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {
            File file = new File(localDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            outStream = new BufferedOutputStream(new FileOutputStream(strFilePath));
            success = this.downloadFile(remoteDir, remoteFileName, outStream);
        } catch (Exception e) {
//            SysLog.log(remoteFileName + "下载失败:" + e.getMessage());
            throw new RuntimeException(remoteFileName + "下载失败:" + e.getMessage());
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    @Override
    public boolean downloadFile(String filePath, OutputStream outStream) throws Exception {
        filePath = filePath.replace("\\", "/").replace("//", "/");
        int i = filePath.lastIndexOf("/");
        String remoteDir = filePath.substring(0, i);
        String remoteFileName = filePath.substring(i + 1);
        return downloadFile(remoteDir, remoteFileName, outStream);
    }

    @Override
    public boolean downloadFile(String remoteDir, String remoteFileName, OutputStream outStream) throws Exception {
        boolean success = false;
        FTPClient ftpClient = getFTPClient();
        try {
            if (!ftpClient.changeWorkingDirectory(concatPath(this.getRoot(), remoteDir))) {
                // 切换工作目录失败
//                return false;
                throw new RuntimeException(remoteDir + "切换工作目录失败:");
            }
            success = ftpClient.retrieveFile(remoteFileName, outStream);
            if (success == true) {
//                SysLog.log(remoteFileName + "成功下载");
                LogUtils.info(remoteFileName + "成功下载","");
                return success;
            }
        } catch (Exception e) {
        	 throw e;
        } finally {
            try {
                returnFTPClient(ftpClient);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (success == false) {
        	 throw new RuntimeException(remoteFileName + "下载失败!");
//            SysLog.log(remoteFileName + "下载失败!");
        }
        return success;
    }

    @Override
    public boolean uploadDirectory(String localDir, String remoteDir) throws Exception {
        File src = new File(localDir);
        FTPClient ftpClient = getFTPClient();
        try {
            remoteDir = concatPath(true, remoteDir, src.getName());
            if (!mdirs(ftpClient, remoteDir, this.getRoot())) {
//                SysLog.log("目录创建失败:" + remoteDir);
//                return false;
                throw new RuntimeException("目录创建失败:" + remoteDir);
            }
        } catch (Exception e) {
//            SysLog.log("目录创建失败:" + remoteDir + ":" + e.getMessage());
//            return false;
            throw new RuntimeException("目录创建失败:" + remoteDir + ":" + e.getMessage());
        } finally {
            try {
                returnFTPClient(ftpClient);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        File[] allFile = src.listFiles();
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                if (!uploadFile(new File(srcName), remoteDir)) {
                    return false;
                }
            }
        }
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                // 递归
                if (!uploadDirectory(allFile[currentFile].getPath().toString(), remoteDir)) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public boolean downLoadDirectory(String remoteDir, String localDir) throws Exception {
        FTPClient ftpClient = getFTPClient();
        FTPFile[] allFile = null;
        try {
            String fileName = new File(remoteDir).getName();
            localDir = concatPath(true, localDir, fileName);
            File dirFile = new File(localDir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            allFile = ftpClient.listFiles(concatPath(this.getRoot(), remoteDir));
        } catch (IOException e) {
//            SysLog.log("下载文件夹失败:" + e.getMessage());
//            return false;
            throw new RuntimeException("下载文件夹失败:" + e.getMessage());
        } finally {
            try {
                returnFTPClient(ftpClient);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (allFile != null && allFile.length > 0) {
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    if (!downloadFile(remoteDir, allFile[currentFile].getName(), localDir)) {
                        return false;
                    }
                }
            }
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    String path = concatPath(remoteDir, allFile[currentFile].getName());
                    if (!downLoadDirectory(path, localDir)) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    @Override
    public boolean delFile(String remoteDir, String storeName) throws Exception {
        return this.delFile(concatPath(remoteDir, storeName));
    }

    @Override
    public boolean delFile(String filePath) throws Exception {
        FTPClient ftpClient = getFTPClient();
        try {
            return ftpClient.deleteFile(concatPath(this.getRoot(), filePath));
        } catch (IOException e) {
//            e.printStackTrace();
//            SysLog.log("删除文件失败:" + e.getMessage());
//            return false;
            throw new RuntimeException("删除文件失败:" + e.getMessage());
        } finally {
            try {
                returnFTPClient(ftpClient);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @author caisf
     * @date 2016年5月26日
     * @param ftpClient
     * @param dirs 待创建目录
     * @return
     */
    private boolean mdirs(FTPClient ftpClient, String dirs) {
        return mdirs(ftpClient, dirs, null);
    }

    /**
     * @author caisf
     * @date 2016年5月26日
     * @param ftpClient
     * @param dirs   待创建目录
     * @param parent   使用相对路径创建
     * @return
     */
    private boolean mdirs(FTPClient ftpClient, String dirs, String parent) {
        if ((dirs == null || "".equals(dirs))) {
            return true;
        }
        try {
            if(!ftpClient.changeWorkingDirectory(parent)){
                return mdirs(ftpClient , concatPath(parent , dirs));
            }
        } catch (Exception e) {
            return false;
        }

        dirs = dirs.replace("\\", "/");
        if (dirs.startsWith("/")) {
            dirs = dirs.substring(1, dirs.length());
        }
        if (dirs.endsWith("/")) {
            dirs = dirs.substring(0, dirs.length() - 1);
        }
        String[] paths = dirs.split("/");
        String currentDir = "";
        try {
            if (!dirs.startsWith("/") && (parent != null && !"".equals(parent))) {
                currentDir = parent.endsWith("/") ? parent : parent + "/";
            } else {
                currentDir = "/";
            }
            for (String dir : paths) {
                currentDir += (dir + "/");
                ftpClient.makeDirectory(currentDir);
            }
            return ftpClient.changeWorkingDirectory(currentDir);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取ftp根目录
     *
     * @author caisf
     * @date 2016年6月1日
     * @return
     */
    private String getRoot() {
        return FTPClientConfigure.getRoot();
    }

    /**
     * 拼凑目录
     *
     * @author caisf
     * @date 2016年6月1日
     * @param paths
     * @return
     */
    public static String concatPath(String... paths) {
        return concatPath(false, paths);
    }

    /**
     * 拼凑目录
     *
     * @author caisf
     * @date 2016年6月1日
     * @param endsWithSlash
     * @param paths
     * @return
     */
    public static String concatPath(Boolean endsWithSlash, String... paths) {
        Assert.notEmpty(paths, "目录不能为空");
        if (paths.length == 1) {
            return paths[0];
        }
        String path = paths[0];
        for (int i = 1; i < paths.length; i++) {
            path = concatPath(path, paths[i], endsWithSlash);
        }
        return path;
    }

    /**
     * 拼凑目录
     *
     * @author caisf
     * @date 2016年6月1日
     * @param parent
     * @param path
     * @param endsWithSlash 以斜杠结尾
     * @return
     */
    public static String concatPath(String parent, String path, Boolean endsWithSlash) {
        Assert.notNull(parent, "目录不能为空");
        Assert.notNull(path, "目录不能为空");
        if (!(parent.endsWith("\\") || parent.endsWith("/"))) {
            parent = parent.concat("/");
        }
        if (!endsWithSlash) {
            return parent.concat(path).replaceAll("//", "/");
        }
        if (!(path.endsWith("\\") || path.endsWith("/"))) {
            return parent.concat(path).concat("/").replaceAll("//", "/");
        } else {
            return parent.concat(path).replaceAll("//", "/");
        }
    }
}











package com.haday.springbootplus.supermarketSys.ftp.pool;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import com.haday.springbootplus.util.DES;

import net.bytebuddy.asm.Advice.This;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;

import com.haday.springbootplus.config.FtpConfig;


/**
 * FtpClient配置类,封装了FtpClient的相关配置
 *
 * @author caisf
 */
@Service
public class FTPClientConfigure {
	
//	@Autowired
	private FtpConfig FtpConfig;
	
	/**
	 * 主机名、ip
	 */
	private String host;

	/**
	 * 端口
	 */
	private int port;

	/**
	 * 用户名
	 */
	private String username;

	/**
	 * 密码
	 */
	private String password;

	/**
	 * 是否被动模式
	 */
	private String passiveMode;

	/**
	 * 编码
	 */
	private String encoding;

	/**
	 * 连接超时时间,可能会受限于具体的ftp服务器
	 */
	private int connectionTimeOut;

	/**
	 * 线程数,ftp连接池数量
	 */
	private int threadNum;

	/**
	 * 是否开启连接池
	 */
	private boolean poolEnable;

	/**
	 * 文件传输类型,默认为二进制
	 */
	private int transferFileType = FTPClient.BINARY_FILE_TYPE;

	/**
	 * 连接池取对象最大等待时间
	 */
	private int poolBorrowWaitLimit;

	/**
	 * 根目录
	 */
	private String root;

	private static Boolean isInit = false;

	
//	private FTPClientConfigure config;
	

	
	@Autowired
	private FTPClientConfigure(FtpConfig FtpConfig) throws Exception {
		this.FtpConfig = FtpConfig;
		if(!isInit){
//			FileInputStream is = null;
			try {
//				System.out.println("config-ftp.properties path==" + FTPClientConfigure.class.getResource("/").getPath());
//				is = new FileInputStream(FTPClientConfigure.class.getResource("/").getPath() + "config-ftp.properties");
//				Properties props=new Properties();
//				props.load(is);
				
				System.out.println("FtpConfig =="  + FtpConfig.toString() );
				
				host = FtpConfig.getHost();
				passiveMode = FtpConfig.getPassiveMode();
				connectionTimeOut = FtpConfig.getConnectionTimeOut();
				encoding = FtpConfig.getEncoding();
				username = FtpConfig.getUsername();
				password = FtpConfig.getPassword();
				port = FtpConfig.getPort();
				transferFileType = FtpConfig.getTransferFileType();
				poolEnable = FtpConfig.isPoolEnable();
				threadNum = FtpConfig.getThreadNum();
				poolBorrowWaitLimit=FtpConfig.getPoolBorrowWaitLimit();
				root= FtpConfig.getRoot();
				try {
					username=DES.decrypt( FtpConfig.getUsername());
					password= DES.decrypt( FtpConfig.getPassword());
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				isInit = true;

//				config.host = props.getProperty("ftp.host");
//				config.passiveMode = props.getProperty("ftp.passiveMode");
//				config.connectionTimeOut = Integer.parseInt(props.getProperty("ftp.connectionTimeOut"));
//				config.encoding = props.getProperty("ftp.encoding");
//				config.username = props.getProperty("ftp.username");
//				config.password = props.getProperty("ftp.password");
//				config.port = Integer.parseInt(props.getProperty("ftp.port"));
//				config.transferFileType = Integer.parseInt(props.getProperty("ftp.transferFileType"));
//				config.poolEnable = Boolean.parseBoolean(props.getProperty("ftp.poolEnable"));
//				config.threadNum = Integer.parseInt(props.getProperty("ftp.threadNum"));
//				config.poolBorrowWaitLimit=Integer.parseInt(props.getProperty("ftp.poolBorrowWaitLimit"));
//				config.root= props.getProperty("ftp.root");
//				try {
//					config.username=DES.decrypt(config.username);
//					config.password= DES.decrypt(config.password);
//				} catch (Exception e) {
//					throw new RuntimeException(e);
//				}
//				isInit = true;
//			} catch (FileNotFoundException e) {
//				throw new RuntimeException(e);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}finally{
//				try {
////					is.close();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
			}

		}
//		return config;
	}
	
	
	
	/**
	 * ftp配置参数
	 */
//	private static FTPClientConfigure config = new FTPClientConfigure();

	
	
	

	
	
//	
//	/**
//	 * 默认配置
//	 * @return
//	 */
//	public static synchronized FTPClientConfigure getConfig(){
//		if(!isInit){
//			FileInputStream is = null;
//			try {
//				System.out.println("config-ftp.properties path==" + FTPClientConfigure.class.getResource("/").getPath());
//				is = new FileInputStream(FTPClientConfigure.class.getResource("/").getPath() + "config-ftp.properties");
//				Properties props=new Properties();
//				props.load(is);
//				
//				System.out.println("FtpConfig ==" + );
//				
//				FtpConfig
//				
//				
//
//				config.host = props.getProperty("ftp.host");
//				config.passiveMode = props.getProperty("ftp.passiveMode");
//				config.connectionTimeOut = Integer.parseInt(props.getProperty("ftp.connectionTimeOut"));
//				config.encoding = props.getProperty("ftp.encoding");
//				config.username = props.getProperty("ftp.username");
//				config.password = props.getProperty("ftp.password");
//				config.port = Integer.parseInt(props.getProperty("ftp.port"));
//				config.transferFileType = Integer.parseInt(props.getProperty("ftp.transferFileType"));
//				config.poolEnable = Boolean.parseBoolean(props.getProperty("ftp.poolEnable"));
//				config.threadNum = Integer.parseInt(props.getProperty("ftp.threadNum"));
//				config.poolBorrowWaitLimit=Integer.parseInt(props.getProperty("ftp.poolBorrowWaitLimit"));
//				config.root= props.getProperty("ftp.root");
//				try {
//					config.username=DES.decrypt(config.username);
//					config.password= DES.decrypt(config.password);
//				} catch (Exception e) {
//					throw new RuntimeException(e);
//				}
//				isInit = true;
//			} catch (FileNotFoundException e) {
//				throw new RuntimeException(e);
//			} catch (IOException e) {
//				throw new RuntimeException(e);
//			}finally{
//				try {
//					is.close();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//
//		}
//		return config;
//	}

	/**
	 * 获取主机名、ip
	 * @return host 主机名、ip
	 */
	public String getHost() {
		return host;
	}

	/**
	 * 设置主机名、ip
	 * @param host 主机名、ip
	 */
	public void setHost(String host) {
		this.host = host;
	}

	/**
	 * 获取端口
	 * @return port 端口
	 */
	public int getPort() {
		return port;
	}

	/**
	 * 设置端口
	 * @param port 端口
	 */
	public void setPort(int port) {
		this.port = port;
	}

	/**
	 * 获取用户名
	 * @return username 用户名
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * 设置用户名
	 * @param username 用户名
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * 获取密码
	 * @return password 密码
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * 设置密码
	 * @param password 密码
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * 获取是否被动模式
	 * @return passiveMode 是否被动模式
	 */
	public String getPassiveMode() {
		return passiveMode;
	}

	/**
	 * 设置是否被动模式
	 * @param passiveMode 是否被动模式
	 */
	public void setPassiveMode(String passiveMode) {
		this.passiveMode = passiveMode;
	}

	/**
	 * 获取编码
	 * @return encoding 编码
	 */
	public String getEncoding() {
		return encoding;
	}

	/**
	 * 设置编码
	 * @param encoding 编码
	 */
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	/**
	 * 获取连接超时时间,可能会受限于具体的ftp服务器
	 * @return connectionTimeOut 连接超时时间,可能会受限于具体的ftp服务器
	 */
	public int getConnectionTimeOut() {
		return connectionTimeOut;
	}

	/**
	 * 设置连接超时时间,可能会受限于具体的ftp服务器
	 * @param connectionTimeOut 连接超时时间,可能会受限于具体的ftp服务器
	 */
	public void setConnectionTimeOut(int connectionTimeOut) {
		this.connectionTimeOut = connectionTimeOut;
	}

	/**
	 * 获取线程数,ftp连接池数量
	 * @return threadNum 线程数,ftp连接池数量
	 */
	public int getThreadNum() {
		return threadNum;
	}

	/**
	 * 设置线程数,ftp连接池数量
	 * @param threadNum 线程数,ftp连接池数量
	 */
	public void setThreadNum(int threadNum) {
		this.threadNum = threadNum;
	}

	/**
	 * 获取文件传输类型,默认为二进制
	 * @return transferFileType 文件传输类型,默认为二进制
	 */
	public int getTransferFileType() {
		return transferFileType;
	}

	/**
	 * 设置文件传输类型,默认为二进制
	 * @param transferFileType 文件传输类型,默认为二进制
	 */
	public void setTransferFileType(int transferFileType) {
		this.transferFileType = transferFileType;
	}

	/**
	 * 获取连接池取对象最大等待时间
	 * @return poolBorrowWaitLimit 连接池取对象最大等待时间
	 */
	public int getPoolBorrowWaitLimit() {
		return poolBorrowWaitLimit;
	}

	/**
	 * 设置连接池取对象最大等待时间
	 * @param poolBorrowWaitLimit 连接池取对象最大等待时间
	 */
	public void setPoolBorrowWaitLimit(int poolBorrowWaitLimit) {
		this.poolBorrowWaitLimit = poolBorrowWaitLimit;
	}

	/**
	 * 获取根目录
	 * @return root 根目录
	 */
	public String getRoot() {
		return root;
	}

	/**
	 * 设置根目录
	 * @param root 根目录
	 */
	public void setRoot(String root) {
		this.root = root;
	}

	/**
	 * 获取是否开启连接池
	 * @return poolEnable 是否开启连接池
	 */
	public boolean isPoolEnable() {
		return poolEnable;
	}

	/**
	 * 设置是否开启连接池
	 * @param poolEnable 是否开启连接池
	 */
	public void setPoolEnable(boolean poolEnable) {
		this.poolEnable = poolEnable;
	}

	public FtpConfig getFtpConfig() {
		return FtpConfig;
	}

	public void setFtpConfig(FtpConfig ftpConfig) {
		FtpConfig = ftpConfig;
	}



//	public FTPClientConfigure getConfig() {
//		return config;
//	}
//
//
//
//	public void setConfig(FTPClientConfigure config) {
//		this.config = config;
//	}

	
	

}














package com.haday.springbootplus.supermarketSys.ftp.pool;

import java.io.IOException;
import java.util.TimeZone;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool.PoolableObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.haday.springbootplus.config.FtpConfig;

/**
 * FTPClient工厂类,通过FTPClient工厂提供FTPClient实例的创建和销毁
 *
 * @author caisf
 */

@Service
public class FTPClientFactory implements PoolableObjectFactory {

	
	
//	@Autowired
	private FTPClientConfigure config;
	
//	/**
//	 * 配置参数
//	 */
//	private FTPClientConfigure config;

//	/**
//	 * @param config 配置参数
//	 */
	@Autowired
	private FTPClientFactory(FTPClientConfigure config) {
		this.config = config;
	}

	@Override
	public FTPClient makeObject() throws Exception {
		return genFtpClient();
	}

	private FTPClient genFtpClient() {
		FTPClient ftpClient = new FTPClient();
		//设置为windows可能会出现找不到目录的情况
		FTPClientConfig ftpClientConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
		ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
		ftpClient.setControlEncoding(config.getEncoding());
		ftpClient.configure(ftpClientConfig);
		try {
			ftpClient.connect(config.getHost(), config.getPort());
			// FTP服务器连接回答
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				throw new RuntimeException("登录FTP服务失败!");
			}
			boolean result = ftpClient.login(config.getUsername(), config.getPassword());
			if (!result) {
				throw new RuntimeException("ftpClient登陆失败! userName:"
						+ config.getUsername() + " ; password:"
						+ config.getPassword());
			}
			// 设置传输协议
			if ("true".equals(config.getPassiveMode())) {
				ftpClient.enterLocalPassiveMode();
			}
			ftpClient.setConnectTimeout(config.getConnectionTimeOut());
			ftpClient.setFileType(config.getTransferFileType());
			/*ftpClient.setSo*/
		} catch (Exception e) {
			throw new RuntimeException("ftpClient登陆失败:"+e.getMessage());
		}
		ftpClient.setBufferSize(1024 * 2);

		return ftpClient;
	}

	/**
	 * 销毁对象
	 */
	@Override
	public void destroyObject(Object obj) throws Exception {
		FTPClient ftpClient = (FTPClient)obj;
		try {
			if (ftpClient != null && ftpClient.isConnected()) {
				ftpClient.logout();
			}
		} catch (IOException io) {
		} finally {
			try {
				ftpClient.disconnect();
			} catch (IOException io) {
				io.printStackTrace();
			}
		}
	}

	/**
	 * 验证对象是否可用
	 */
	@Override
	public boolean validateObject(Object obj) {
		FTPClient ftpClient = (FTPClient)obj;
		try {
			return ftpClient.sendNoOp();
		} catch (IOException e) {
			return false;
		}
	}
	@Override
	public void activateObject(Object obj) throws Exception {
	}
	@Override
	public void passivateObject(Object obj) throws Exception {

	}

//	private static FTPClientFactory instance = new FTPClientFactory(FTPClientConfigure.getConfig());

//	public static FTPClientFactory getInstance(){
//		return instance;
//	}

	/**
	 * 获取配置参数
	 * @return config 配置参数
	 */
	public FTPClientConfigure getConfig() {
		return config;
	}


}








package com.haday.springbootplus.supermarketSys.ftp.pool;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import javax.annotation.PreDestroy;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 实现了一个FTPClient连接池
 *
 * @author caisf
 */

@Service
public class FTPClientPool implements ObjectPool {
	
	
//	@Autowired
	private FTPClientFactory factory;
	
	
//	@Autowired
	private FTPClientConfigure config;
	
	
	
//	private static final int DEFAULT_POOL_SIZE = FTPClientConfigure.getConfig().getThreadNum();
	private  BlockingQueue<FTPClient> pool;
//	private final FTPClientFactory factory;

//	private FTPClientPool() throws Exception{
//		this(DEFAULT_POOL_SIZE, FTPClientFactory.getInstance());
//	}

//	/**
//	 * 初始化连接池,需要注入一个工厂来提供FTPClient实例
//	 *
//	 * @param factory
//	 * @throws Exception
//	 */
//	private FTPClientPool(FTPClientFactory factory) throws Exception {
//		this(DEFAULT_POOL_SIZE, factory);
//	}

//	/**
//	 *
//	 * @param poolSize
//	 * @param factory
//	 * @throws Exception
//	 */
//	private FTPClientPool(int poolSize, FTPClientFactory factory)
//			throws Exception {
//		int poolSize = config.getThreadNum();
//		
//		
//		this.factory = factory;
//		pool = new ArrayBlockingQueue<FTPClient>(poolSize);
//		initPool(poolSize);
//	}

	
	/**
	 *
	 * @param poolSize
	 * @param factory
	 * @throws Exception
	 */
	
	@Autowired
	private FTPClientPool( FTPClientFactory factory,FTPClientConfigure config) throws Exception {
		this.config=config;
		this.factory=factory;
		 if(config.isPoolEnable()){
			 int poolSize = config.getThreadNum();
			pool = new ArrayBlockingQueue<FTPClient>(poolSize);
			initPool(poolSize);
		 }
	}

	


	/**
	 * 初始化连接池,需要注入一个工厂来提供FTPClient实例
	 *
	 * @param maxPoolSize
	 * @throws Exception
	 */
	public void initPool(int maxPoolSize) throws Exception {
		for (int i = 0; i < maxPoolSize; i++) {
			addObject();
		}

	}

	/**
	 * 获取连接对象,注意需要归还
	 *
	 * @throws Exception
	 */
	@Override
	public FTPClient borrowObject() throws Exception {
		FTPClient client = pool.poll(this.getConfig().getPoolBorrowWaitLimit(), TimeUnit.SECONDS);
		if (client == null) {
			//超过3s未获取对象则抛出异常
			throw new RuntimeException("服务器忙,请稍后再试");
		} else if (!factory.validateObject(client)) {// 验证不通过
			// 使对象在池中失效
			invalidateObject(client);
			// 重新制造对象
			client = factory.makeObject();
		}
		return client;

	}

	/**
	 * 归还对象
	 *
	 * @throws Exception
	 */
	@Override
	public void returnObject(Object obj) throws Exception {
		FTPClient client = (FTPClient)obj;
		if ((client != null) && !pool.offer(client, this.getConfig().getPoolBorrowWaitLimit(), TimeUnit.SECONDS)) {
			try {
				factory.destroyObject(client);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 连接对象失效时调用
	 *
	 * @throws Exception
	 */
	@Override
	public void invalidateObject(Object obj) throws Exception {
		// 移除无效的客户端
		FTPClient client = (FTPClient)obj;
		pool.remove(client);
		try {
			factory.destroyObject(client);
		} catch (Exception e) {
		}
	}

	/**
	 * 往池中添加对象
	 * @throws Exception
	 */
	@Override
	public void addObject() throws Exception, IllegalStateException,
			UnsupportedOperationException {
		pool.offer(factory.makeObject(), this.getConfig().getPoolBorrowWaitLimit(), TimeUnit.SECONDS);
	}

	@Override
	public int getNumIdle() throws UnsupportedOperationException {
		return 0;
	}
	@Override
	public int getNumActive() throws UnsupportedOperationException {
		return 0;
	}
	@Override
	public void clear() throws Exception, UnsupportedOperationException {

	}

	/**
	 * 销毁容器时,销毁池
	 * @throws Exception
	 */
	@PreDestroy
	@Override
	public void close() throws Exception {
		while (pool.iterator().hasNext()) {
			FTPClient client = pool.take();
			factory.destroyObject(client);
		}
	}


	/**
	 * 获取配置参数
	 * @return config 配置参数
	 */
	public FTPClientConfigure getConfig() {
		return this.factory.getConfig();
	}

	@Override
	public void setFactory(PoolableObjectFactory factory)
			throws IllegalStateException, UnsupportedOperationException {
	}


//	private static FTPClientPool instance ;

	/**
	 * 获取单例对象
	 * @author caisf
	 * @date 2016年6月1日
	 * @return
	 */
//	public static synchronized FTPClientPool getInstance(){
//		if(instance == null){
//			try {
//				instance = new FTPClientPool();
//			} catch (Exception e) {
//				throw new RuntimeException(e);
//			}
//		}
//		return instance;
//	}

}







function ajaxDownFile(url, data, fileName) {
	commonConsole(url, "ajaxDownFile url");
	commonConsole(data, "ajaxDownFile data");
	var dataParam = data;
	// var dataParam = getAjaxPostDataFormatParam(data);
	commonConsole(dataParam, "ajaxPost dataParam");


	var loadingIndex = openLoading("下载中");
	var url = url;
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true); // 也可以使用POST方式,根据接口
	xhr.setRequestHeader('Content-type', 'application/json;charset=utf-8');
	xhr.responseType = "blob"; // 返回类型blob
	// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
	xhr.onload = function () {
		closeLoading(loadingIndex);
		// 请求完成
		// if (this.status != 200) {
			// var sucessFlag = xhr.getResponseHeader('sucessFlag');

			// if (sucessFlag != 1) {
				var downFileErrorMsg = xhr.getResponseHeader('downFileErrorMsg');

				if(commonJs.objectIsNotEmpty(downFileErrorMsg)){
					downFileErrorMsg = decodeURI(downFileErrorMsg);
					commonConsole(downFileErrorMsg, "ajaxDownFile downFileErrorMsg");
					openAlert("文件下载失败,请联系管理员");
					return;
				}


			// }
		// }


		var blob = new Blob([this.response]);
		if ('msSaveOrOpenBlob' in navigator) {
			//ie使用的下载方式
			window.navigator.msSaveOrOpenBlob(blob, fileName);
		} else {
			commonConsole(blob, "ajaxDownFile blob");
			var link = document.createElement('a');
			link.href = window.URL.createObjectURL(blob);
			link.download = fileName;
			link.click();
		}
	};
	// 发送ajax请求
	xhr.send(JSON.stringify(dataParam));


}



  @Override
    public void downAgreementFiles(DownAgreementFilesParam param) throws Exception {

        ZipOutputStream zipOutputStream = null;
        File zipFile = null;

        BufferedInputStream bis = null;
        BufferedOutputStream out = null;
        FileInputStream in = null;

        try {
            if (param == null) {
                throw new RuntimeException("param 为空");
            }

            LogUtils.info(param, "param");
            // =============
            String uuid = StringUtils.getUuid();
            String zipFileName = uuid + ".zip";
            String path = request.getSession().getServletContext().getRealPath("/");
            LogUtils.info(path, "path");
//			String zipPath = path + "userfiles/uploadFile/" + zipFileName;// 避免重复下载时读取旧文件
            String zipPath = path +"/temp/"+ zipFileName;// 避免重复下载时读取旧文件
            LogUtils.info(zipPath, "zipPath");
            // ----------
            zipFile = new File(zipPath); //

            zipOutputStream = ZipUtils.getZipOutputStream(zipFile);

            List<String> khIdList = param.getKhIdList();

            if (ObjectValidityUtils.isNullOrEmpty(khIdList)) {
                throw new RuntimeException("要下载的khId列表为空");
            }

            for (String khId : khIdList) {

                String sql = new BaseScanSqlCommand().getSqlText(this, "AgreementServiceImpl.xml", "downAgreementFiles");
                sql = sql.replaceAll("##khId##", khId);

                List<Map<String, Object>> mapList = manageServ.getCommonServ1().getListMapObjBySQL(sql);

                if (mapList == null || mapList.size() == 0) {
                    throw new RuntimeException("khId == " + khId + "协议信息不存在");
                }

                for (Map<String, Object> mapTemp : mapList) {
                    String filePath = StringUtils.toNotNullString(mapTemp.get("filePath"));
                    if (!ObjectValidityUtils.isNullOrEmpty(filePath)) {

                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

                        fileInfoService.downloadByFilePath(filePath, outStream, "7");

//                        boolean flag = ftpService.downloadFile(filePath, ddmKhCheckAttachment.getAttachmentName(), byteArrayOutputStream, "7");
                        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                        LogUtils.info(fileName, "fileName");
                        fileName = khId + "/" + fileName; //

                        ZipUtils.setFileDataToZipOutputStream(zipOutputStream, fileName, outStream);
                    }
                }
            }
            zipOutputStream.close();// 记得关闭资源

            in = new FileInputStream(new File(zipPath));
            bis = new BufferedInputStream(in);
            out = new BufferedOutputStream(response.getOutputStream());

//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 128];
            int n = -1;
            while ((n = bis.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            out.flush();
        } catch (Exception e) {
            LogUtils.error(e);

            if (zipOutputStream != null) {
//                zipOutputStream.closeEntry();
                zipOutputStream.close();
            }
            if (zipFile != null) {
                boolean flag = zipFile.delete();
                LogUtils.info(flag, "zipFile delete flag");
                if (flag) {
                    LogUtils.info("文件已删除(异常)", "");
                } else {
                    LogUtils.info("文件未删除(异常)", "");
                }
            }
//			LogUtils.error(e);
            response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionBySize(e, 1800));// 设置头部信息
            response.sendError(200, "");
        } finally {
            if (bis != null) {
                bis.close();
            }

            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }

            if (zipOutputStream != null) {
//                zipOutputStream.closeEntry();
                zipOutputStream.close();
            }

            boolean flag = zipFile.delete();
            LogUtils.info(flag, "zipFile delete flag");
            if (flag) {
                LogUtils.info("文件已删除", "");
            } else {
                LogUtils.info("文件未删除", "");
            }
        }
    }






package com.haday.ssp.service.supermarketSys.fileupload.impl;

import java.io.*;
import java.util.*;
import java.util.zip.ZipOutputStream;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.haday.ssp.service.manage.service.ManageServ;
import com.haday.ssp.service.supermarketSys.attach.FileInfoService;
import com.haday.ssp.service.supermarketSys.attach.impl.FtpAttachServiceImpl;
import com.haday.ssp.service.supermarketSys.fileupload.FileUploadService;
import com.haday.ssp.service.supermarketSys.fileupload.param.DeleteFileParam;
import com.haday.ssp.service.supermarketSys.fileupload.param.GetFilesParam;
import com.haday.ssp.utils.supermarket.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service("FileUploadServiceImpl")
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private FtpAttachServiceImpl ftpAttachServiceImpl;


    @Autowired
    protected HttpServletRequest request; // 这里可以获取到request

    @Autowired
    protected HttpServletResponse response; // 这里可以获取到response

    @Autowired
    private FileInfoService fileInfoService;

//    @Autowired
//    private ManageServ manageServ;

//	@Autowired
//	private AttachInfoService AttachInfoService;


    @Override
    public Object fileUpload(MultipartFile file, String ftpKey, String remoteDir, String fileName) throws Exception {

        File uploadFile = null;
        try {
//			 产品目录
//            String uuid = request.getParameter("busField");
            if (file == null) {
                ExceptionUtils.throwRuntimeException("上传文件为空");
            }
            if (ftpKey == null) {
                ExceptionUtils.throwRuntimeException("上传ftpKey为空");
            }
            if (remoteDir == null) {
                remoteDir = "";
            }
            if (fileName == null) {
                ExceptionUtils.throwRuntimeException("上传FileName为空");
            }

            // ----------------
            String originalFilename = file.getOriginalFilename();

//            describe = StringUtils.toNotNullString(describe) + ",原文件名:" + originalFilename;
            LogUtils.info(originalFilename, "OriginalFilename");

            if ("".equals(StringUtils.toNotNullString(fileName))) {
                fileName = StringUtils.getUuid() + FileUtils.getExtendName(file.getOriginalFilename());
            } else {
                fileName = fileName + "_" + StringUtils.getUuid() + FileUtils.getExtendName(file.getOriginalFilename());
            }
            LogUtils.info(fileName, "fileName");
            //
//						// ----------------
            //
            uploadFile = new File(fileName); // 创建了一个File对象没有创建文件
            FileUtil.writeFromStream(file.getInputStream(), uploadFile);
            //
            String storeName = fileName;


            String storeFilePath = fileInfoService.saveAttach(uploadFile, remoteDir, storeName, ftpKey);

            Object object = ResultUtils.getSuccessResult(storeFilePath);

            return object;

        } catch (Exception e) {
            LogUtils.error(e);
            return ResultUtils.getErrorResult(e);
        } finally {
            if (uploadFile != null) {
                // 会在本地产生临时文件,用完后需要删除
                if (uploadFile.exists()) {
                    FileUtil.del(uploadFile);
                }
            }
        }
    }


    @Override
    public Object deleteFile(DeleteFileParam param) throws Exception {

        LogUtils.info(param, "deleteFile");
        try {
            String ftpKey = param.getFtpKey();

            if (ObjectValidityUtils.isNullOrEmpty(ftpKey)) {
                throw new RuntimeException("ftpKey为空");
            }

            List<String> filePathList = param.getFilePathList();

            ObjectValidityUtils.checkNotEmpty(filePathList, "删除文件ID");


            fileInfoService.delAttachByFilePathList(filePathList, ftpKey);


            Object object = ResultUtils.getSuccessResult("");
            LogUtils.info(object, "deleteFile return object");
            return object;

        } catch (Exception e) {
            LogUtils.error(e);
            return ResultUtils.getErrorResult(e);
        } finally {

        }
    }


    @Override
    public void getFile(String ftpKey, String filePath) throws Exception {
        try {
            if (ObjectValidityUtils.isNullOrEmpty(ftpKey)) {
                ExceptionUtils.throwRuntimeException("ftpKey为空");
            }
            if (ObjectValidityUtils.isNullOrEmpty(filePath)) {
                ExceptionUtils.throwRuntimeException("filePath为空");
            }
            String fileName = "";
            if (filePath.indexOf("/") > -1) {
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            } else {
                fileName = filePath;
            }

            String name = fileName;

            String fileOutName = new String(name.getBytes("UTF-8"), "ISO8859-1");
            response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息

            fileInfoService.downloadByFilePath(filePath, response.getOutputStream(), ftpKey);

            response.getOutputStream().flush();
        } catch (Exception e) {
            LogUtils.error(e);
            response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionBySize(e, 1800));// 设置头部信息
            response.sendError(200, "");
        } finally {

        }
    }


    @Override
    public void getFiles(GetFilesParam param) throws Exception {
        ZipOutputStream zipOutputStream = null;
        File zipFile = null;

        BufferedInputStream bis = null;
        BufferedOutputStream out = null;
        FileInputStream in = null;

        try {
            if (param == null) {
                throw new RuntimeException("param 为空");
            }

            LogUtils.info(param, "param");

            String ftpKey = param.getFtpKey();

            if (ObjectValidityUtils.isNullOrEmpty(ftpKey)) {
                throw new RuntimeException("ftpKey为空");
            }

            // =============
            String uuid = StringUtils.getUuid();
            String zipFileName = uuid + ".zip";
            String path = request.getSession().getServletContext().getRealPath("/");
            LogUtils.info(path, "path");
//			String zipPath = path + "userfiles/uploadFile/" + zipFileName;// 避免重复下载时读取旧文件
            String zipPath = path + "/temp/" + zipFileName;// 避免重复下载时读取旧文件
            LogUtils.info(zipPath, "zipPath");
            // ----------
            zipFile = new File(zipPath); //

            zipOutputStream = ZipUtils.getZipOutputStream(zipFile);

            List<String> filePathList = param.getFilePathList();

            if (ObjectValidityUtils.isNullOrEmpty(filePathList)) {
                throw new RuntimeException("要下载的filePathList列表为空");
            }

            for (String filePath : filePathList) {
                if (!ObjectValidityUtils.isNullOrEmpty(filePath)) {

                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

                    fileInfoService.downloadByFilePath(filePath, outStream, ftpKey);

//                        boolean flag = ftpService.downloadFile(filePath, ddmKhCheckAttachment.getAttachmentName(), byteArrayOutputStream, "7");
                    String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                    LogUtils.info(fileName, "fileName");
//                    fileName = khId + "/" + fileName; //

                    ZipUtils.setFileDataToZipOutputStream(zipOutputStream, fileName, outStream);
                }
            }
            zipOutputStream.close();// 记得关闭资源

            in = new FileInputStream(new File(zipPath));
            bis = new BufferedInputStream(in);
            out = new BufferedOutputStream(response.getOutputStream());

//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 128];
            int n = -1;
            while ((n = bis.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            out.flush();
        } catch (Exception e) {
            LogUtils.error(e);

            if (zipOutputStream != null) {
//                zipOutputStream.closeEntry();
                zipOutputStream.close();
            }
            if (zipFile != null) {
                boolean flag = zipFile.delete();
                LogUtils.info(flag, "zipFile delete flag");
                if (flag) {
                    LogUtils.info("文件已删除(异常)", "");
                } else {
                    LogUtils.info("文件未删除(异常)", "");
                }
            }
//			LogUtils.error(e);
            response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionBySize(e, 1800));// 设置头部信息
            response.sendError(200, "");
        } finally {
            if (bis != null) {
                bis.close();
            }

            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }

            if (zipOutputStream != null) {
//                zipOutputStream.closeEntry();
                zipOutputStream.close();
            }

            boolean flag = zipFile.delete();
            LogUtils.info(flag, "zipFile delete flag");
            if (flag) {
                LogUtils.info("文件已删除", "");
            } else {
                LogUtils.info("文件未删除", "");
            }
        }
    }

}





package com.haday.ssp.controller.supermarketSys.fileUpload.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.haday.ssp.service.supermarketSys.fileupload.FileUploadService;
import com.haday.ssp.service.supermarketSys.fileupload.param.DeleteFileParam;
import com.haday.ssp.service.supermarketSys.fileupload.param.GetFilesParam;
import com.haday.ssp.utils.supermarket.ExceptionUtils;
import com.haday.ssp.utils.supermarket.LogUtils;
import com.haday.ssp.utils.supermarket.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Api("附件管理")
@RequestMapping("/fileController")
public class FileController {

//	public static final String DBKEY = "44";

    @Autowired
    FileUploadService fileUploadService;

//
//    @Autowired
//    AttachInfoMapper attachInfoMapper;

//	@Autowired
//	FtpService ftpService;

//    @Autowired
//    private ManageServ manageServ;

//    @Autowired
//    private LoadDataServiceImpl loadDataServiceImpl;

    @Autowired
    protected HttpServletRequest request; // 这里可以获取到request
    @Autowired
    protected HttpServletResponse response;


    @PostMapping("/fileUpload")
    @ApiOperation(value = "附件上传", notes = "列表", response = String.class)
    @ResponseBody
    public Object fileUpload(@RequestParam("file") MultipartFile file, @RequestParam String ftpKey,
                             @RequestParam String remoteDir, @RequestParam String fileName) throws Exception {
        File uploadFile = null;
        try {
            return fileUploadService.fileUpload(file, ftpKey, remoteDir, fileName);
        } catch (Exception e) {
            LogUtils.error(e);
            return ResultUtils.getErrorResult(e);
        } finally {
            if (uploadFile != null) {
                // 会在本地产生临时文件,用完后需要删除
                if (uploadFile.exists()) {
                    FileUtil.del(uploadFile);
                }
            }
        }

    }

    @PostMapping("/deleteFile")
    @ApiOperation(value = "附件删除", notes = "附件删除", response = String.class)
    @ResponseBody
    public Object deleteFile(@RequestBody DeleteFileParam param) throws Exception {
        try {
            return fileUploadService.deleteFile(param);
        } catch (Exception e) {
            LogUtils.error(e);
            return ResultUtils.getErrorResult(e);
        } finally {

        }
    }

//    @PostMapping("/getFileList")
//    @ApiOperation(value = "附件列表", notes = "附件列表", response = String.class)
//    @ResponseBody
//    public Object getFileList(@RequestBody com.haday.springbootplus.supermarketSys.fileUpload.param.GetFileListParam param) throws Exception {
//        LogUtils.info(param, "getFileList");
//        try {
//            if (param.getDbKey() == null) {
//                ExceptionUtils.throwRuntimeException("上传DbKey为空");
//            }
//
//            String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFileList");
//
//            Paging paging = loadDataServiceImpl.getPageData(sql, param.getDbKey(), param.getGetListParam());
//
//            Object object = ResultUtils.getSuccessResult(paging);
//            LogUtils.info(object, "getFileList return object");
//            return object;
//
//        } catch (Exception e) {
//            LogUtils.error(e);
//            return ResultUtils.getErrorResult(e);
//        } finally {
//
//        }
//    }

    @GetMapping("/getFile")
    @ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
    @ResponseBody
    public void getFile(String ftpKey, String filePath) throws Exception {

        try {
            fileUploadService.getFile(ftpKey, filePath);
        } catch (Exception e) {
            LogUtils.error(e);
            response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionBySize(e, 1800));// 设置头部信息
            response.sendError(200, "");
        } finally {

        }
    }

    @PostMapping("/getFiles")
    @ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
    @ResponseBody
    public void getFiles(@RequestBody GetFilesParam param) throws Exception {
        try {
            fileUploadService.getFiles(param);
        } catch (Exception e) {
            LogUtils.error(e);
            response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionBySize(e, 1800));// 设置头部信息
            response.sendError(200, "");
        }
    }

}

































































分享到:
评论

相关推荐

    基于Python+Django简单实现文件上传下载功能源码.zip

    基于Python+Django简单实现文件上传下载功能源码 基于Python+Django简单实现文件上传下载功能源码 基于Python+Django简单实现文件上传下载功能源码 基于Python+Django简单实现文件上传下载功能源码 基于...

    局域网文件上传下载工具

    【局域网文件上传下载工具】是一个实用的软件应用,主要设计用于在局域网内的设备之间方便地进行文件的上传和下载操作。这个工具强调的是简单易用和跨平台特性,使得用户无论是在Windows、Mac还是Linux系统上都能...

    C# WinForm 文件上传下载

    总的来说,C# WinForm文件上传下载的实现涉及网络操作、文件处理、数据库交互等多个方面,需要对C#语言和相关技术有深入理解。通过`WebClient`类,我们可以轻松地完成基本的文件上传下载功能,但为了提供更健壮、...

    delphi做的文件上传下载服务器端

    标题 "delphi做的文件上传下载服务器端" 描述了一个使用Delphi编程语言开发的服务器程序,该程序专门设计用于处理文件的上传和下载功能。在IT领域,这样的系统通常涉及网络编程、多线程和并发处理,以确保能有效地...

    通用文件上传下载接口使用说明.docx

    本文档主要介绍了通用文件上传下载接口的使用说明,包括文件上传和文件下载两个部分。在文件上传部分,我们需要关注文件主键id,它是文件上传的唯一标识符,上传文件时将返回该id,以便后续下载和删除操作。 文件...

    C#webapi文件上传下载源码

    在这个场景下,"C# WebAPI文件上传下载源码"指的是使用C#编写的一套实现文件上传和下载功能的WebAPI服务代码。 文件上传功能是Web应用中的常见需求,允许用户将本地文件传输到服务器。在C# WebAPI中,这通常通过...

    基于jsp的文件上传下载

    "基于jsp的文件上传下载"是Web应用程序中的常见需求,涉及到客户端与服务器之间的数据交互。本项目详细阐述了如何利用JSP实现文件的上传和下载功能。 首先,文件上传涉及的主要技术有HTML表单、Servlet和多部分请求...

    struts实现的文件上传下载功能

    总结起来,使用Struts实现文件上传下载涉及前端表单设计、后端处理逻辑、文件存储策略以及安全控制等多个方面。在实践中,我们还需要考虑到性能优化和用户体验提升,例如使用异步上传、进度条展示等技术。

    文件上传下载demo

    在IT行业中,文件上传下载是Web应用中常见且重要的功能之一。这个"文件上传下载demo"项目显然聚焦于实现这一功能,并对一个名为jspSmartUpload的组件进行了优化处理,特别是针对SmartUpload类进行升级,解决了文件名...

    struts2文件上传下载源代码

    这篇博客文章提供的"struts2文件上传下载源代码"旨在帮助开发者理解和实现这些功能。 文件上传功能允许用户从他们的设备上传文件到服务器。在Struts2中,这通常通过表单实现,表单包含一个`&lt;input type="file"&gt;`...

    Bootstrap自定义文件上传下载样式

    总结起来,Bootstrap自定义文件上传下载样式涉及的关键技术包括Bootstrap的样式和组件(如`.input-group`、`.input-group-addon`),HTML5的文件上传API,Font Awesome图标库,以及CSS3的`pointer-events`属性。...

    利用jsp实现文件上传下载

    JSP 实现文件上传下载 在本文中,我们将学习如何使用 JSP 实现文件上传和下载功能。在这个过程中,我们将使用 Apache 的 Commons FileUpload 和 Commons IO 两个库来处理文件上传和下载。 首先,让我们了解一下...

    Jsp文件上传下载

    总结来说,JSP文件上传下载是通过SmartUpload库实现的,它简化了文件操作的复杂性,使得开发者能更专注于业务逻辑。通过理解和实践SmartUpload的用法,你将能够为你的Web应用添加这一关键功能。同时,理解文件上传...

    文件上传下载需要的jar包 java文件上传下载

    在这个场景下,"文件上传下载需要的jar包"指的是用于处理文件上传和下载操作的Java类库。下面将详细介绍相关的知识点。 1. **Apache Commons FileUpload**: 这是一个非常流行的Java库,用于处理HTTP请求中的多部分...

    tomcat 实现文件上传下载

    以上就是使用Struts2和Tomcat实现文件上传下载的基本流程。实际开发中,还需要考虑文件大小限制、多文件上传、错误处理、安全问题(如防止路径遍历攻击)等。通过这个示例,你可以了解到Struts2框架如何与Tomcat配合...

    嵌入式Linux下基于CGI的文件上传下载的实现

    ### 嵌入式Linux下基于CGI的文件上传下载实现 #### 1. 概述 随着嵌入式Linux的深入研究和发展,其在各领域的应用变得越来越广泛。嵌入式Linux是一种针对特定应用场景进行了裁剪和优化的Linux版本,能够适应资源...

    文件上传下载(C#+Sql2008)

    【文件上传下载(C#+Sql2008)】是一个基于C#编程语言和SQL Server 2008数据库的程序,旨在实现文件的上传和下载功能。在Web开发中,这样的功能通常用于用户交互,比如用户上传自己的文档、图片或者其他数据到服务器...

    基于Struts2的文件上传下载功能的完整源代码。

    在基于Struts2的文件上传下载功能中,它提供了处理用户上传文件和提供文件下载的服务。这个完整的源代码是实现这些功能的一个实例,经过测试确保了其正确性和可用性。 首先,我们要理解Struts2中的Action类。Action...

    文件上传下载8个源码示例

    在IT行业中,文件上传下载是Web应用的基本功能之一,它涉及到客户端与服务器之间的数据交互。本资源包提供了8个源码示例,旨在帮助开发者快速掌握文件上传和下载的实现方式。下面,我们将深入探讨这些知识点。 1. *...

Global site tag (gtag.js) - Google Analytics