◆JAVA/SPRING + JAVA

[JAVA]FTP 서버 업로드

쿠키린 2023. 6. 14. 12:31

commons-net-3.9.0.jar
0.30MB

⬇️ FTP 서버 연결 설정 및 연동 , 업로드만 구현했음

package egovframework.onpia.crm.sms.util;

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 java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.SocketException;


public class FTPControl { // FTP 연결, 파일 업로드 등을 수행하는 메서드
    private static final Logger logger = LoggerFactory.getLogger(FTPControl.class);

    /**FTP 서버로 파일을 업로드
     * @Param : 서버 정보(server,port), 인증 정보(username, password), 로컬파일 경로, 원격파일 경로*/
    public static void uploadFile(String server, int port, String username, String password, String localFilePath, String remoteFilePath) throws Exception {
        FTPClient ftpClient = new FTPClient(); // FTP 연결과 파일 전송에 사용된다.

        //localFilePath : 전송하려는 파일이 저장된 로컬 시스템(클라이언트)에서의 파일 경로 의미
        //remoteFilePath : 파일을 전송하고자 하는 원격시스템(FTP)에서의 파일 경로를 의미 ( 전송하려는 파일이 FTP 서버에서 어느 위치에 저장될지를 지정)

        FileInputStream fileInputStream = null;
        try {
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.connect(server, port);//서버정보

            int resultCode = ftpClient.getReplyCode();//접속확인

            if (!FTPReply.isPositiveCompletion(resultCode)) {// 응답 false이면 연결해제
                logger.error("[FTP] Server refused connection.");
                ftpClient.disconnect();//연결해제
                return;

            }else{

                if(!(ftpClient.login(username, password))){//로그인
                    logger.error("[FTP] Login error");
                    return;
                }

                logger.info("[FTP] Success connection.");
                logger.info("[FTP] Login successful.");
            }
            ftpClient.setSoTimeout(1000);		//Timeout 설정 (기본이 1분 = 60000)
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//이진 파일 타입 설정(이미지파일을 전송시에는 전송타입 변경 필요)
            ftpClient.enterLocalPassiveMode();// Active 모드 설정
           // ftpClient.changeWorkingDirectory(remoteFilePath);
            if (!(ftpClient.changeWorkingDirectory(remoteFilePath))) {//저장파일경로
                logger.error("[FTP] Failed to change working directory.");
                return;
            }

            File localFile = new File(localFilePath);//로컬 파일 경로 기반으로 File 객체 생성

            fileInputStream = new FileInputStream(localFile);
            if (ftpClient.storeFile(localFile.getName(), fileInputStream)){// 전송 - ftp 서버에 파일 업로드
                logger.info("[FTP] Image uploaded successfully.");
            } else {
                logger.error("[FTP] Failed to upload image.");
            }


        }catch (FileNotFoundException fe){
            logger.error("[FTP] File not Found. =>",fe.getMessage());
            fe.printStackTrace();
        }catch (SocketException se){
            logger.error("[FTP] Socket Error. =>",se.getMessage());
            se.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {

            try{
                if(fileInputStream != null){
                    fileInputStream.close();
                }
                //로그아웃
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }

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

        }
    }
}

⬇️호출

try{
   //FTP 서버에 전송
   FTPControl.uploadFile(ftpServer,iFtpPort, ftpUsername, ftpPassword,  realPath + "/" + strContentImg1New, strFTPImgPath);
} catch(Exception e) {
	e.printStackTrace();
}

 

ftpServer : FTP 서버 IP주소

iFtpPort : 21 (FTP 서버 기존 포트)

ftpUsername: username(계정)

ftpPassword: password(계정)

realPath+"/"+strContentImag1New : 로컬경로/사진명

strFTPImagePath : 리모트 경로 즉, FTP서버 업로드할 저정 경로 ex) /상위경로/하위경로

 

 

+

저는 setting.properties파일을 만들어서 거기다가 정보들을 입력하여

정보를 가져오는 방식을 사용했습니다.(이유  : 수정하기 편리하기 위해서)