개발 기록

JAVA SFTP 파일 업로드/삭제 본문

JAVA

JAVA SFTP 파일 업로드/삭제

수염차 2024. 5. 10. 15:21

https://jmseo.tistory.com/entry/Java-SFTP-Util-sftp-%EC%97%85%EB%A1%9C%EB%93%9C-%EB%8B%A4%EC%9A%B4%EB%A1%9C%EB%93%9C-%EC%98%88%EC%A0%9C-jsch

 

[Java] SFTP 파일 업로드, 다운로드 예제 (jsch)

이전에 K사와 sftp 송수신으로 가맹점정보 파일을 다운로드, 결제정보를 업로드하여 파일처리하는 업무를 하며 개발했던 소스를 포스팅한당.. 앞서 jsch 라이브러리를 사용하면 쉽게 SFTP 서버 접

jmseo.tistory.com

 

SFTPHelper.java (연결, 종료, 파일 업로드, 삭제)

@Log4j2
@Component
class SFTPHelper {

    private Session session;
    private Channel channel;
    private ChannelSftp channelSftp;

    public void sftpInit(String ip, int port, String id, String pw, String privateKey) throws Exception {
        int timeout = 20000; 	//타임아웃 20초

        JSch jsch = new JSch();
        try {

            //key 인증방식일경우
            if(null != privateKey && !"".equals(privateKey)) {
                jsch.addIdentity(privateKey);
            }

            //세션객체 생성
            session = jsch.getSession(id, ip, port);

            if(null == privateKey || "".equals(privateKey)) {
                session.setPassword(pw); //password 설정
            }

            //세션관련 설정정보 설정
            java.util.Properties config = new java.util.Properties();

            //호스트 정보 검사하지 않는다.
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setTimeout(timeout); //타임아웃 설정

            log.info("[SFTPUtil.sftpInit] connect.. " + ip);
            session.connect();	//접속

            channel = session.openChannel("sftp");	//sftp 채널 접속
            channel.connect();

        } catch (JSchException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
        channelSftp = (ChannelSftp) channel;
    }


    /**
     * SFTP 서버 접속 종료
     */
    public void disconnect() {
        if(channelSftp != null) {
            channelSftp.quit();
        }
        if(channel != null) {
            channel.disconnect();
        }
        if(session != null) {
            session.disconnect();
        }
    }

    /**
     * SFTP 서버 파일 업로드
     */
    public void sftpUploadFile(String uploadPath, File file, String uploadFileNm) throws Exception {
        FileInputStream in = null;

        try{
            //파일을 가져와서 inputStream에 넣고 저장경로를 찾아 업로드
            in = new FileInputStream(file);
            channelSftp.cd(uploadPath);
            channelSftp.put(in,uploadFileNm);
        } catch (Exception e) {
            throw e;
        } finally{
            try{
                in.close();
            } catch(IOException ioe){
            }
        }
    }

    /**
     * SFTP 서버 파일 삭제
     */
    public void sftpDeleteFile(String filePath) throws SftpException {
        try {
            channelSftp.rm(filePath);
        } catch (Exception e) {
            throw e;
        }
    }
}

 

 

SFPTHandler.java

@Component
@RequiredArgsConstructor
@Slf4j
public class SFTPHandler implements FileServerHandler {

    private final SFTPHelper sftpHelper;

    private final SystemDao systemDao;

    private String sftpId;
    private String sftpIp;
    private int sftpPort;
    private String sftpPw;
    private String uploadLink;

    @Override
    public void uploadFile(String uploadPath, File file, String uploadFileNm) throws FailUploadException {
        setSFTPConfig();

        try {
            // sftp 접속하여 파일 서버에 이미지 업로드
            sftpHelper.sftpInit(sftpIp, sftpPort, sftpId, sftpPw, "");
            sftpHelper.sftpUploadFile(uploadLink + uploadPath, file, uploadFileNm); //파일 업로드
            sftpHelper.disconnect();
        } catch (Exception e) {
            log.error("" + e, e);
            throw new FailUploadException("파일 업로드에 실패했습니다.");
        }

    }

    @Override
    public void deleteFile(String filePath) throws FailDeleteException {
        setSFTPConfig();

        try {
            //sftp 서버 파일 삭제
            sftpHelper.sftpInit(sftpIp, sftpPort, sftpId, sftpPw, "");
            sftpHelper.sftpDeleteFile(uploadLink + filePath);
            sftpHelper.disconnect();
        } catch (Exception e) {
            log.error("" + e, e);
            throw new FailDeleteException("파일 삭제에 실패했습니다.");
        }


    }

    @Override
    public void updateFile(String filePath, String uploadPath, File file, String uploadFileNm) throws FailUpdateException {
        setSFTPConfig();

        try {
            // 파일서버에서 이미지 삭제 후 재등록
            sftpHelper.sftpInit(sftpIp, sftpPort, sftpId, sftpPw, "");
            sftpHelper.sftpDeleteFile(uploadLink + filePath);
            sftpHelper.sftpUploadFile(uploadLink + uploadPath, file, uploadFileNm); //파일 업로드
            sftpHelper.disconnect();
        } catch (Exception e) {
            log.error("" + e, e);
            throw new FailUpdateException("파일 수정에 실패했습니다.");
        }

    }
    
    /**
     * sftp 서버 정보 설정
     */
    private void setSFTPConfig() {
        List<ConfigVo> configVos = systemDao.selectConfig(); // 전체 config 조회
        Map<String, String> map = configVos.stream()
                .collect(Collectors.toMap(ConfigVo::getConfigKey, ConfigVo::getConfigValue));

        sftpId = map.get(FileServerConstant.FILE_SERVER_ID);
        sftpPw = map.get(FileServerConstant.FILE_SERVER_PW);
        sftpIp = map.get(FileServerConstant.FILE_SERVER_IP);
        sftpPort = Integer.parseInt(map.get(FileServerConstant.FILE_SERVER_PORT));
        uploadLink = map.get(FileServerConstant.FILE_UPLOAD_LINK);
    }
}

'JAVA' 카테고리의 다른 글

[이펙티브 자바] 아이템2  (0) 2024.08.31
[이펙티브 자바] 아이템1  (0) 2024.08.26
java.util.logging.logger 사용법  (0) 2023.10.18
upcasting, downcasting  (0) 2023.01.26
super()  (0) 2023.01.26
Comments