본문 바로가기
Java

[Java] SFTP 파일 전송(업로드) 구현(JSch 사용)

by jn4624 2022. 4. 26.
반응형

1. SFTP 전송시 필요한 정보

  • User Ip
  • User Port
  • User Id
  • User Password
  • Upload Path

 

2. sendSFTP 메소드 구현

public void sendSftp(HashMap<String, Object> map) {
    try {
        String originFileName = (String) map.get("fileName");
        String zipFileName = originFileName.substring(0, originFileName.lastIndexOf(".")) + ".zip";

        String sftpIp = configService.getConfigValue("IP");
        int sftpPort = Integer.parseInt(configService.getConfigValue("PORT"));
        String sftpUserId = configService.getConfigValue("USER_ID");
        String sftpUserPw = configService.getConfigValue("USER_PW");
        String sftpFilePath = configService.getConfigValue("UPLOAD_PATH");

        Session session = null;
        JSch jsch = new JSch();

        session = jsch.getSession(sftpUserId, sftpIp, sftpPort);
        session.setPassword(sftpUserPw);

        java.util.Properties config = new java.util.Properties();
        // ssh_config에 호스트 key 없이 접속 가능토록 property 설정
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        ChannelSftp channelSftp = null;
        Channel channel = null;

        FileInputStream in = null;

        try {
            channel = session.openChannel("sftp");
            channel.connect();

            channelSftp = (ChannelSftp) channel;

            File file = new File(uploadPath, zipFileName);

            in = new FileInputStream(file);

            channelSftp.cd(sftpFilePath);
            channelSftp.put(in, file.getName());

            // Zip파일 RNAME 처리
            File newZipFile = new File(uploadPath, zipFileName+".back");
            file.renameTo(newZipFile);

            // 원본파일 RNAME 처리
            File originFile = new File(uploadPath, originFileName);
            File newOriginFile = new File(uploadPath, originFileName+".back");
            originFile.renameTo(newOriginFile);
        } catch( Exception e ) {
            e.printStackTrace();
        } finally {
            in.close();
            channelSftp.exit();
            channel.disconnect();
            session.disconnect();
        }
    } catch( Exception e ) {
        e.printStackTrace();
    }
}

 

 

🙏 참조 ::

반응형