fairnet/src/main/java/seed/com/gtm/seedfile/SeedFileController.java

434 lines
16 KiB
Java

package seed.com.gtm.seedfile;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import seed.com.gtm.util.CommonsCompress;
import seed.com.gtm.util.JSPUtil;
import egovframework.rte.psl.dataaccess.util.EgovMap;
import seed.utils.SeedDateUtil;
import seed.utils.SeedProperties;
import seed.utils.SeedUtils;
@Controller
public class SeedFileController {
@Autowired
private SeedFileService service;
protected Log log = LogFactory.getLog(this.getClass());
@RequestMapping(value="/seed/extra/temp/file.do", method=RequestMethod.POST)
public @ResponseBody HashMap<String, Object> tempFileUpload(HttpSession session, HttpServletRequest req, MultipartHttpServletRequest mreq){
String siteIdx = SeedUtils.setReplaceNull(session.getAttribute("siteIdx"));
if(siteIdx.equals("")){
siteIdx = SeedUtils.setReplaceNull(req.getParameter("siteIdx"));
}
// 파일 멀티로 받음
//MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
Iterator<String> fileNames = mreq.getFileNames();
String funcType = req.getParameter("fileFuncType");
String copyContractYn = SeedUtils.setReplaceNull(req.getParameter("copyContractYn"));
String fileName = "";
String reFileName = "";
String fileType = "";
Long fileSize = 0L;
boolean success = false;
SeedProperties seedProperties = new SeedProperties();
String tempPath = "";
if(funcType.equals("trublchargermng")){
tempPath = seedProperties.getConfigValue("root.path");
}else{
tempPath = seedProperties.getConfigValue("file.temp.path");
}
//SeedUtils.setSeedMkDirs(rootPath + "/" + siteIdx + "/upload/tempFiles/"+funcType);
/*MultipartFile uploadFile = null;
if(copyContractYn.equals("Y")){
uploadFile = mreq.getFile("upFile");
}else if(copyContractYn.equals("N")){
uploadFile = mreq.getFile("upFile2");
}else{
uploadFile = mreq.getFile("upFile");
}
System.out.println("2222");*/
while(fileNames.hasNext())
{
String fileNm = fileNames.next();
MultipartFile mFile = mreq.getFile(fileNm);
SeedDateUtil seedDateUtil = new SeedDateUtil();
//File Null Check
if(mFile.getSize()!=0){
fileName = mFile.getOriginalFilename();
reFileName = funcType+"_" + seedDateUtil.getSimpleDateFormat(new Date(), "yyyyMMddHHmmss") + "_" + SeedUtils.getSeedMD5Code(String.valueOf(SeedUtils.getRandom(999,1)));
fileType = mFile.getOriginalFilename().substring(mFile.getOriginalFilename().lastIndexOf(".")+1);
if (!Pattern.matches("(?i)^[\\d\\D]*\\.(txt|jpeg|jpg|png|gif|bmp|mp3|mp4|hwp|doc|docx|xls|xlsx|ppt|pptx|pdf|zip|alz)$","."+fileType)) {
success = false;
session.setAttribute("sSiteIdx", siteIdx);
session.setAttribute("message", "(message)해당 파일은 업로드 하실수 없습니다.");
session.setAttribute("self", "history");
session.setAttribute("url", "");
}else{
reFileName = reFileName+"."+fileType;
File makeFile = null;
if(funcType.equals("trublchargermng")){
//위원회 사지파일만 site 밑으로 저장
makeFile = new File(tempPath+"/"+siteIdx+"/upload/tempFiles/"+funcType+"/"+reFileName);
}else{
makeFile = new File(tempPath+"/"+siteIdx+"/"+funcType+"/"+reFileName);
}
log.warn(tempPath+"/"+siteIdx+"/"+funcType+"/"+reFileName);
//경로상에 파일이 존재하지 않을 경우
if(! makeFile.exists()){
//경로에 해당하는 디렉토리들을 생성
if(makeFile.getParentFile().mkdirs()){
try {
makeFile.createNewFile(); //이후 파일 생성
} catch (IOException e) {
// TODO Auto-generated catch block
log.warn("SeedFileController 템프파일 업로드 에러1");
}
}
}
try {
mFile.transferTo(makeFile); //임시로 저장된 multipartFile을 실제 파일로 전송
} catch (IllegalStateException e) {
log.warn("SeedFileController 템프파일 업로드 에러2");
} catch (IOException e) {
log.warn("SeedFileController 템프파일 업로드 에러3");
}
fileSize = mFile.getSize();
success = true;
}
}
/*if(uploadFile!=null && !uploadFile.isEmpty()){
SeedDateUtil seedDateUtil = new SeedDateUtil();
fileName = uploadFile.getOriginalFilename();
reFileName = funcType+"_" + seedDateUtil.getSimpleDateFormat(new Date(), "yyyyMMddHHmmss") + "_" + SeedUtils.getSeedMD5Code(String.valueOf(SeedUtils.getRandom(999,1)));
fileType = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf(".")+1);
if (!Pattern.matches("(?i)^[\\d\\D]*\\.(txt|jpeg|jpg|png|gif|bmp|mp3|mp4|hwp|doc|docx|xls|xlsx|ppt|pptx|pdf|zip|alz)$","."+fileType)) {
success = false;
session.setAttribute("sSiteIdx", siteIdx);
session.setAttribute("message", "(message)해당 파일은 업로드 하실수 없습니다.");
session.setAttribute("self", "history");
session.setAttribute("url", "");
}else{
reFileName = reFileName+"."+fileType;
File makeFile = new File(rootPath+"/"+siteIdx+"/upload/tempFiles/"+funcType+"/"+reFileName);
System.out.println(rootPath+"/"+siteIdx+"/upload/tempFiles/"+funcType+"/"+reFileName);
try {
uploadFile.transferTo(makeFile);
} catch (IllegalStateException e) {
System.out.println("SeedFileController 템프파일 업로드 에러");
} catch (IOException e) {
System.out.println("SeedFileController 템프파일 업로드 에러");
}
fileSize = uploadFile.getSize();
success = true;
}
}*/
}
//JSON 변환을 위한 맵
HashMap<String, Object> fileInfo = new HashMap<String, Object>();
fileInfo.put("fileName",fileName);
fileInfo.put("reFileName",reFileName);
fileInfo.put("fileSize",fileSize);
fileInfo.put("fileType",fileType);
fileInfo.put("funcType",funcType);
fileInfo.put("copyContractYn",copyContractYn);
return fileInfo;
}
@RequestMapping("/seed/extra/down/file.do")
public ModelAndView fileDown(ModelMap map, HttpSession session ,HttpServletResponse response,HttpServletRequest request,@RequestParam Map<String,Object> paramMap){
SeedProperties seedProperties = new SeedProperties();
String rootPath = seedProperties.getConfigValue("file.real.path");
String dataIdx = SeedUtils.setReplaceNull(paramMap.get("dataIdx"));
String pathKey1 = SeedUtils.setReplaceNull(paramMap.get("pathKey1"));
String pathKey2 = SeedUtils.setReplaceNull(paramMap.get("pathKey2"));
String funcType = SeedUtils.setReplaceNull(paramMap.get("funcType"));
if(funcType.equals("trublchargermng")){
rootPath = seedProperties.getConfigValue("root.path");
}
String path = SeedUtils.setReplaceNull(paramMap.get("filePath"));
pathKey1 = SeedUtils.setFilePathReplaceAll(pathKey1);
pathKey2 = SeedUtils.setFilePathReplaceAll(pathKey2);
funcType = SeedUtils.setFilePathReplaceAll(funcType);
String fileReName = "";
String fileName = "";
String filePath = rootPath + "/" + pathKey1 + "/"+funcType;
if(!"".equals(dataIdx) && !"".equals(funcType)){
//funcType이 download일 경우 download폴더 하위의 일반 파일 및 특정 파일을 다운로드 하는 로직으로 동작 하게 됩니다.
if("download".equals(funcType)){
fileReName = dataIdx;
fileName = dataIdx;
filePath = rootPath + "/" + pathKey1 + "/"+funcType;
}else if("mediation".equals(funcType) || "trublreqstmng".equals(funcType) || "trublcfrncmng".equals(funcType)){
Map<String, Object> fileList = service.caseFileOne(paramMap);
fileReName = SeedUtils.setReplaceNull(fileList.get("FILE_ORGNAME"));
fileName = SeedUtils.setReplaceNull(fileList.get("FILE_NAME"));
if(SeedUtils.setReplaceNull(paramMap.get("downUserl")).equals("user")){
//본인인증 시간 체크
if(SeedUtils.setReplaceNull(session.getAttribute("isGubun")).equals("")){
return new ModelAndView("redirect:/user/mediation/case/01/155/checkMediationStep01.do");
}
if(!SeedUtils.setReplaceNull(session.getAttribute("hpName")).equals("")){
paramMap.put("fileNo", SeedUtils.setReplaceNull(fileList.get("FILE_NO")));
paramMap.put("seqNo", SeedUtils.setReplaceNull(fileList.get("SEQ_NO")));
paramMap.put("hpName", SeedUtils.setReplaceNull(session.getAttribute("hpName")));
paramMap.put("isGubun", SeedUtils.setReplaceNull(session.getAttribute("isGubun")));
service.hisInsert(paramMap);
}
}
if(funcType.equals("trublchargermng")){
filePath = rootPath + "/" + pathKey1 + "/upload/uploadFiles/"+funcType+"/"+pathKey2;
}else{
filePath = rootPath + "/" + pathKey1 + "/"+funcType+"/"+pathKey2;
}
}else{
Map<String, Object> fileList = service.fileOne(paramMap);
fileReName = SeedUtils.setReplaceNull(fileList.get("EXTRA_FILE_RENAME"));
fileName = SeedUtils.setReplaceNull(fileList.get("EXTRA_FILE_NAME"));
if(funcType.equals("trublchargermng")){
filePath = rootPath + "/" + pathKey1 + "/upload/uploadFiles/"+funcType+"/"+pathKey2;
}else{
filePath = rootPath + "/" + pathKey1 + "/"+funcType+"/"+pathKey2;
}
}
}
ModelAndView mv = new ModelAndView("filedownLoad");
mv.addObject("fileReName", fileReName);
mv.addObject("fileName", fileName);
mv.addObject("filePath", filePath);
return mv;
}
@RequestMapping("/seed/extra/down/filedown.do")
public ModelAndView fileDown(HttpServletResponse response, HttpSession session, HttpServletRequest request)throws Exception{
EgovMap params;
params = JSPUtil.makeRequestParams(request, session, true);
log.warn(">>>>>>>>params<<<<<<<<<"+params);
SeedProperties seedProperties = new SeedProperties();
String fileOrgname = SeedUtils.setReplaceNull(params.get("fileOrgname"));
String fileName = SeedUtils.setReplaceNull(params.get("fileName"));
String filePath = SeedUtils.setReplaceNull(params.get("filePath"));
ModelAndView mv = new ModelAndView("filedownLoad");
mv.addObject("fileReName", fileOrgname);
mv.addObject("fileName", fileName);
mv.addObject("filePath", filePath);
return mv;
}
@RequestMapping("/seed/extra/down/zipfile.do")
public ModelAndView zipfileDown(HttpServletResponse response, HttpSession session, HttpServletRequest request)throws Exception{
EgovMap params;
params = JSPUtil.makeRequestParams(request, session, true);
log.warn(">>>>>>>>params<<<<<<<<<"+params);
SeedProperties seedProperties = new SeedProperties();
SeedDateUtil seedDateUtil = new SeedDateUtil();
String rootPath = seedProperties.getConfigValue("file.real.path");
String pathKey = SeedUtils.setReplaceNull(params.get("pathKey"));
String filePath = rootPath + "/" + pathKey + "/zipDown/" + params.get("memberId").toString()+"/"+seedDateUtil.getSimpleDateFormat(new Date(), "yyyyMMdd");
String fileCopyPath = rootPath + "/" + pathKey + "/zipDown/"
+ params.get("memberId").toString()+"/"+seedDateUtil.getSimpleDateFormat(new Date(), "yyyyMMdd")
+"/"+params.get("rceptNo").toString();
System.out.println("filePath:" + filePath);
System.out.println("fileCopyPath: "+fileCopyPath);
List <File> filelist = new ArrayList<File>();
List fileList = service.caseFileListEgov(params);
String fileGubunNm = "";
File orgFile = new File(filePath);
File copyFile = new File(fileCopyPath);
if(!orgFile.exists()){
//경로에 해당하는 디렉토리들을 생성
orgFile.mkdirs();
}
if(!copyFile.exists()){
//경로에 해당하는 디렉토리들을 생성
copyFile.mkdirs();
}
if(orgFile.exists() && copyFile.exists()){
for(int i = 0; i < fileList.size(); i++){
//System.out.println(i);
EgovMap emap = new EgovMap();
emap.putAll((EgovMap) fileList.get(i));
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
//파일복사
try {
//FileInputStream fis = new FileInputStream(emap.get("filePath").toString()+emap.get("fileOrgname").toString());
if(emap.get("fileFunc").toString().equals("mediation")){
if(emap.get("filePath").toString().indexOf(".") <= -1){
fis = new FileInputStream(emap.get("filePath").toString() + "/" + emap.get("fileOrgname").toString());
}else{
fis = new FileInputStream(emap.get("filePath").toString());
}
}else{
fis = new FileInputStream(emap.get("filePath").toString() + "/" + emap.get("fileOrgname").toString());
}
fos = new FileOutputStream(fileCopyPath+"/"+emap.get("fileName").toString());
bufferedInputStream = new BufferedInputStream(fis);
bufferedOutputStream = new BufferedOutputStream(fos);
byte[] readBuffer = new byte[1024];
int data = 0;
//System.out.println("111111111");
while(bufferedInputStream.read(readBuffer, 0, readBuffer.length) != -1) {
//fos.write(data);
//System.out.println("aaaaaa");
bufferedOutputStream.write(readBuffer);
//System.out.println("bbbbbbb");
}
//System.out.println("22222222222");
} catch (IOException e) {
// TODO Auto-generated catch block
//여기서 에러남?
e.printStackTrace();
}finally{
try
{
// 파일 닫기. 여기에도 try/catch가 필요하다.
// 보조스트림을 닫으면 원스트림도 닫힌다.
if(bufferedInputStream != null){
bufferedInputStream.close();
}
if(bufferedOutputStream != null){
bufferedOutputStream.close();
}
if(fis != null){
fis.close();
}
if(fos != null){
fos.close();
}
}
catch (Exception e)
{
System.out.println("close failed!!!" + e);
}
}
filelist.add(new File(fileCopyPath+"/"+emap.get("fileName").toString()));
fileGubunNm = emap.get("fileGubunNm").toString();
}
}
Random generator = new Random();
String zipNm = params.get("rceptNo").toString()+"("+fileGubunNm+")_"+ seedDateUtil.getSimpleDateFormat(new Date(), "yyyyMMddHHmmss") + ".zip";
File zippedFile = new File (filePath);
//File zippedFile = new File (filePath, zipNm);
if(!zippedFile.exists()){
//경로에 해당하는 디렉토리들을 생성
zippedFile.mkdirs();
}
if(zippedFile.exists()){
zippedFile = new File (filePath+"/"+zipNm);
try {
//이후 파일 생성
CommonsCompress commonscompress = new CommonsCompress();
commonscompress.zip(filelist, new BufferedOutputStream(new FileOutputStream(zippedFile)) );
} catch (IOException e) {
// TODO Auto-generated catch block
log.warn("SeedFileController error1");
}
}
ModelAndView mv = new ModelAndView("filedownLoad");
mv.addObject("fileReName", zipNm);
mv.addObject("fileName", zipNm);
mv.addObject("filePath", filePath);
return mv;
}
}