본문 바로가기
develop/java

JAVA 파일 업로드 및 썸네일 생성 및 FTP 파일 업로드

by hybr1d 2016. 5. 18.

package com.chorok.mgreen.common.service;


import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.net.SocketException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;


import javax.imageio.ImageIO;


import org.apache.commons.lang.StringUtils;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPReply;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;


import com.chorok.mgreen.common.dao.FileDAO;

import com.chorok.mgreen.common.model.FileVO;


/**

 * @Project : 초록마을 모바일 시스템 구축 프로젝트

 * @FileName : FileServiceImpl.java

 * @Package : com.chorok.mgreen.common.service

 * @Comment : 

 * @작성자 : 조한영

 * @작성일 : 2016. 5. 11. 오후 1:39:09

 * --------------------  Change History ------------------

 * Date              Programmer                 Description

 * 2016. 5. 11.         조한영

 * ---------------------------------------------------------

 */

@Service(value="fileService")

public class FileServiceImpl implements FileService{


/** Logger */

private static final Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class);

@Autowired

private FileDAO fileDAO;

public static final String FILE_SEP = System.getProperty("file.separator");

public static final String REMOTE_URL = "http://attach.choroki.com";

public static final String TEMP_PATH = "/home/jboss/mobile/uploads/temp_file";

public static final String FTP_HOST = "61.111.54.134";

public static final int FTP_PORT = 2100;

public static final String FTP_USER = "chorokimg";

public static final String FTP_PASS = "qwer!234";

public static final String FTP_URL = "http://attach.choroki.com/";

@Override

public String fileUpload(List<MultipartFile> mf, String pakageName, String muid) throws Exception {

LOGGER.debug("START FILE UPLOAD");

FileVO fileVO = new FileVO();

String server = ""; 

String orgFilename = ""; 

String filename = "";

String extension = ""; 

String ftpFolder = "";

Date today = new Date();

File files = null;

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

try {

int regdate = (int) Math.floor(today.getTime()/1000);

            String savePath = "";

if (mf.size() == 1 && mf.get(0).getOriginalFilename().equals("")) {

            

       } else {

        for(MultipartFile multi : mf) {

        if(multi.getSize() > 0) {

        File dir = new File("C:/mgreen/mobile/uploads/temp_file/");

               if (!dir.isDirectory()) {

                   dir.mkdirs();

               }

               /**

                * step 1 - 임시 저장 , 파일 이름 설정  

                */

               orgFilename = multi.getOriginalFilename();

//                savePath = REMOTE_URL + TEMP_PATH + "/"; //실제 서버

               

               String currentDate = format.format(today);

               

               String year = currentDate.substring(0, 4);

               String month = currentDate.substring(4, 6);

               String day = currentDate.substring(6, 8);

               

               //앞이 0이면 한자리로

               if(month.substring(0, 1).equals("0")) {

                month = month.replace("0", "");

               }

               //앞이 0이면 한자리로

               if(day.substring(0, 1).equals("0")) {

                day = day.replace("0", "");

               }

               

               //확장자 구하기

               int fileIndex = StringUtils.lastIndexOf(orgFilename, '.');

               

               if(fileIndex != -1) {

                extension = StringUtils.substring(orgFilename, fileIndex + 1);

               }

               

               //파일 중복 처리

               fileVO.setMuid(muid);

               int sortNo = fileDAO.selectAttachfilesLastMuid() ;

               

               //server 네임 설정 - 2016/3/21/trysumer_69927_103510_ed.jpg /년/월/일 [ 월/일 정보가 1자리 일경우 1자리로 : ex) 05/03 -> 5/3 ]

               server = year + "/" + month +"/" + day +"/" + pakageName + "_" + muid + "_" + sortNo +"_ed." + extension;

               filename = pakageName + "_" + muid + "_" + sortNo +"_ed." + extension; //변형된 파일 네임

               ftpFolder =  "/" + year + "/" + month +"/" + day +"/" ; //FTP FOLDER

               LOGGER.debug("server : "+server);

               

               //VO SET

               

               fileVO.setFilename(orgFilename);

               fileVO.setFilesize(String.valueOf( multi.getSize()));

               fileVO.setRegdate(String.valueOf(regdate));

               fileVO.setSeckey("BOARD");

               fileVO.setFileext(extension);

               fileVO.setServer(server);

               

               savePath = "C:"+File.separator+"mgreen"+File.separator+"mobile"+File.separator+"uploads"+File.separator+"temp_file"+File.separator + filename; // TEST 저장 될 파일 경로

  

               files = new File(savePath);

               

               multi.transferTo(files); // 임시 파일 저장

               

               createFileThumbnail(files, ftpFolder, filename);

               /**

                * step 2 - FTP 접속

                */

               String result = ftpConnect(ftpFolder, filename, files);

               LOGGER.debug("ftp result "+result);

               /**

                * DB 저장 및 파일 삭제

                */

               if(result.equals("success")) {

                if(files.exists()){

                files.delete();

                LOGGER.debug("파일 삭제");

                   }

                fileDAO.insertAttachfiles(fileVO); //파일 정보 디비 저장

                LOGGER.debug("DB 저장"+fileVO.toString());

               

               } else if(result.equals("fail")) {

                return "file send fail";

               }

               

               LOGGER.debug("result : "+result);

        }

       

        }

       }

} catch(Exception e) {

e.printStackTrace();

}

LOGGER.debug("END FILE UPLOAD");

return "success";

}


/**

* @Method Name : ftpConnect

* @Method description : FTP 접속 및 파일 전송

* @작성일 : 2016. 5. 11. 

* @작성자 : 조한영

* ------------------------------ Change History -----------------

* Modification Log :

* Date            Programmer                Description

* 2016. 5. 11.       조한영       

* -----------------------------------------------------------------

* @param year

* @param month

* @param day

* @param savePath

* @param files

*/

public String ftpConnect(String ftpFolder, String filename, File files) {

FTPClient ftp = null;

FileInputStream fis = null;

boolean isSuccess = false;

int reply = 0;

ftp = new FTPClient();

try {

ftp.connect(FTP_HOST,FTP_PORT);

//success

reply = ftp.getReplyCode();

 

if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

LOGGER.debug("FTP server refused connection.");

System.exit(1);

}

 

if(!ftp.login(FTP_USER, FTP_PASS)) {

                ftp.logout();

                LOGGER.debug("ftp 서버에 로그인하지 못했습니다.");

            }

            

            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            ftp.enterLocalPassiveMode();

            ftp.makeDirectory(ftpFolder);

            ftp.changeWorkingDirectory(ftpFolder);

            

            LOGGER.debug("directory : "+ftp.printWorkingDirectory());

            

            //파일 업로드

            String tempFileName = new String((ftpFolder+filename).getBytes("utf-8"),"iso_8859_1");

            

            fis = new FileInputStream(files);

            LOGGER.debug("start send tempFileName  "+tempFileName);

            

            isSuccess = ftp.storeFile(tempFileName, fis);  

            LOGGER.debug("send file RESULT :   "+isSuccess);

            

            

} catch (SocketException e) {

e.printStackTrace();

return "SocketException";

} catch (IOException e) {

e.printStackTrace();

return "IOException";

} finally {

if(fis != null) {

try {

fis.close();

ftp.disconnect();

LOGGER.debug("FTP DISCONNECT   ");

if (!isSuccess) {

return "fail";

}

} catch (IOException e) {

e.printStackTrace();

}

}

return "success";

}


@Override

public List<FileVO> selectBoardFileList(FileVO vo) throws Exception {

return fileDAO.selectBoardFileList(vo); //파일 정보 디비 저장

}


@Override

public void deleteAttachfiles(FileVO vo) throws Exception {

fileDAO.deleteAttachfiles(vo); //파일 정보 디비 저장

}

public void createFileThumbnail(File file, String folder, String fileName) throws Exception {

String thumbPath = "C:/www/mgreen/src/main/webapp/common/images/thumbnail";

File thumbDir = new File(thumbPath+folder);

        if (!thumbDir.isDirectory()) {

        thumbDir.mkdirs();

        }

try {

           //썸네일 가로사이즈

           int thumbnail_width = 100;

           //썸네일 세로사이즈

           int thumbnail_height = 100;

           //생성할 썸네일파일의 경로+썸네일파일명

           File thumb_file_name = new File(thumbPath+folder+fileName);

 

           BufferedImage buffer_original_image = ImageIO.read(file);

           BufferedImage buffer_thumbnail_image = new BufferedImage(thumbnail_width, thumbnail_height, BufferedImage.TYPE_3BYTE_BGR);

           Graphics2D graphic = buffer_thumbnail_image.createGraphics();

           graphic.drawImage(buffer_original_image, 0, 0, thumbnail_width, thumbnail_height, null);

           ImageIO.write(buffer_thumbnail_image, "jpg", thumb_file_name);

           LOGGER.debug("썸네일 생성완료");

       } catch (Exception e) {

           e.printStackTrace();

       }

}

}



'develop > java' 카테고리의 다른 글

JAVA API 호출  (0) 2017.12.20
poi 기본 샘플  (0) 2017.11.20
JAVA - 주소로 위경도 및 격자좌표 구하기  (0) 2016.12.27
월 일별로 데이터 넣기  (0) 2016.11.01
형변환  (0) 2014.11.19