티스토리 뷰

오늘은 JSch 를 이용하여 특정 사이트에서 이미지를 다운받아 SFTP 로 이미지 전송하는 간단한 소스를 작성해보겠습니다.

1. 라이브러리 추가

implementation 'com.jcraft:jsch:0.1.55'
implementation 'commons-net:commons-net:3.10.0'

 

2. 이미지 파일 체크

  • 특정 사이트에 이미지 파일이 있는지 체크합니다.
public boolean existFile(String checkUrl) {
    HttpURLConnection connection = null;
    try {
      URL url = new URL(checkUrl);
      connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("HEAD");

      // 연결 상태 코드 확인
      int responseCode = connection.getResponseCode();

      // 200 OK 상태 코드인 경우 파일이 존재함
      return responseCode == HttpURLConnection.HTTP_OK;
    } catch (Exception e) {
      // 예외 발생 시 파일이 존재하지 않음
      log.error("이미지 파일 없음 : " + checkUrl);
      return false;
    } finally {
      // 연결 해제
      if (connection != null) {
        connection.disconnect();
      }
    }
  }

 

3. 파일 다운로드

public void downImage(String imageUrl, String destinationFile) {
    try {
      URL url = new URL(imageUrl);
      URLConnection conn = url.openConnection();

      InputStream inputStream = conn.getInputStream();
      OutputStream outputStream = new FileOutputStream(destinationFile);

      byte[] buffer = new byte[2048];
      int length;
      while ((length = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, length);
      }

      outputStream.close();
      inputStream.close();

      log.info("이미지 다운로드 완료 : " + imageUrl);
    } catch (Exception e) {
      log.error("이미지 다운로드 실패 : " + imageUrl);
    }
}

 

4. SFTP 이미지 전송

private static void sendImage(String localFilePath, String p_ftpIp, 
	String p_ftpId, String p_ftpPw, String p_ftpPath) {
    
    JSch jsch = new JSch();
    Session session = null;
    ChannelSftp channelSftp = null;

    try {
      // 세션 설정
      session = jsch.getSession(p_ftpId, p_ftpIp, 22);
      session.setPassword(p_ftpPw);
      session.setConfig("StrictHostKeyChecking", "no");
      session.connect();

      // SFTP 채널 열기
      channelSftp = (ChannelSftp) session.openChannel("sftp");
      channelSftp.connect();

      // 로컬 파일 업로드
      File localFile = new File(localFilePath);
      String remoteFileName = localFile.getName();
      String remoteFilePath = p_ftpPath + "/" + remoteFileName;

      channelSftp.put(new FileInputStream(localFile), remoteFilePath);
      log.info("SFTP 전송 성공 [remoteFilePath] : " + remoteFilePath);
    } catch (Exception e) {
      // 오류 로깅
      log.error(e.getMessage());
      log.error("SFTP 전송 실패 [localFilePath] : " + localFilePath);
    } finally {
      // 연결 종료
      if (channelSftp != null) {
        channelSftp.disconnect();
      }
      if (session != null) {
        session.disconnect();
      }
    }
}

 

감사합니다.

최근에 올라온 글
Total
Today
Yesterday