Java

java 에서 ftp 접속 파일 다운로드, 업로드, 삭제 코드

박진만 2012. 10. 29. 12:53
반응형

ftp 접속 파일 다운로드

public static int download(String filePath, String fileName, HttpServletRequest request) throws Exception {
  FTPClient client = null;
  BufferedOutputStream bos = null;
  File fPath  = null;
  File fDir = null;
  File f   = null; 
  
  String url  = PropertiesHandler.getValue("FTP_URL"); //서버 ip 
  String id  = PropertiesHandler.getValue("FTP_ID"); // ftp 접속 id
  String pwd  = PropertiesHandler.getValue("FTP_PWD"); // ftp 접속 비밀번호
  String port = PropertiesHandler.getValue("FTP_PORT"); //ftp 포트
  String downloadPath = request.getSession().getServletContext().getRealPath("/") + PropertiesHandler.getValue("FTP_PATH"); //다운로드 경로
  
  int result = -1;
  
  try{
   // download 경로에 해당하는 디렉토리 생성  
   downloadPath = downloadPath + filePath;  
   fPath     = new File(downloadPath);
   fDir   = fPath;
   fDir.mkdirs();
   
   f = new File(downloadPath, fileName);
   
   client = new FTPClient();
   client.setControlEncoding("UTF-8");
   client.connect(url, Integer.parseInt(port));
   
   int resultCode = client.getReplyCode();
   if (FTPReply.isPositiveCompletion(resultCode) == false){
    client.disconnect();
    throw new CommonException("FTP 서버에 연결할 수 없습니다.");
   }
   else 
   {
    client.setSoTimeout(5000);
    boolean isLogin = client.login(id, pwd);
    
    if (isLogin == false){
     throw new CommonException("FTP 서버에 로그인 할 수 없습니다.");
    }
    
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.changeWorkingDirectory(filePath);
    
    bos = new BufferedOutputStream(new FileOutputStream(f));
    boolean isSuccess = client.retrieveFile(fileName, bos);
    
    if (isSuccess){
     result = 1; // 성공     
    }
    else{
     throw new CommonException("파일 다운로드를 할 수 없습니다.");
    }    
    
    client.logout();    
   } // if ~ else
  } 
  catch (Exception e){
   throw new CommonException("FTP Exception : " + e);
  }
  finally{  
   if (bos != null) try {bos.close();} catch (Exception e) {}     
   if (client != null && client.isConnected()) try {client.disconnect();} catch (Exception e) {}
   
   return result;
  } // try ~ catch ~ finally
 } // download()

ftp 접속 파일 업로드

 public static int upload(String localFilePath, String remoteFilePath, String fileName, HttpServletRequest request) throws Exception {
  
  FTPClient ftp = null; // FTP Client 객체
  FileInputStream fis = null; // File Input Stream
  File uploadfile = new File(localFilePath); // File 객체
  
  String url  = PropertiesHandler.getValue("FTP_URL");  
  String id  = PropertiesHandler.getValue("FTP_ID");
  String pwd  = PropertiesHandler.getValue("FTP_PWD"); 
  String port = PropertiesHandler.getValue("FTP_PORT");
  
  int result = -1;
  try{          
      ftp = new FTPClient(); // FTP Client 객체 생성
      ftp.setControlEncoding("UTF-8"); // 문자 코드를 UTF-8로 인코딩
      ftp.connect(url, Integer.parseInt(port)); // 서버접속 " "안에 서버 주소 입력 또는 "서버주소", 포트번호
      ftp.login(id, pwd); // FTP 로그인 ID, PASSWORLD 입력
      ftp.enterLocalPassiveMode(); // Passive Mode 접속일때 
      ftp.changeWorkingDirectory(remoteFilePath); // 작업 디렉토리 변경
      ftp.setFileType(FTP.BINARY_FILE_TYPE); // 업로드 파일 타입 셋팅
      
      try{
          fis = new FileInputStream(uploadfile); // 업로드할 File 생성
          boolean isSuccess = ftp.storeFile(fileName, fis); // File 업로드
          
          if (isSuccess){
     result = 1; // 성공     
    }
    else{
     throw new CommonException("파일 업로드를 할 수 없습니다.");
    }
      } catch(IOException ex){
          System.out.println("IO Exception : " + ex.getMessage());
      }finally{
          if (fis != null){
              try{
                  fis.close(); // Stream 닫기
                  return result;
                  
              }
              catch(IOException ex){
                  System.out.println("IO Exception : " + ex.getMessage());
              }
          }
      }
      ftp.logout(); // FTP Log Out
  }catch(IOException e){
      System.out.println("IO:"+e.getMessage());
  }finally{
      if (ftp != null && ftp.isConnected()){
          try{
              ftp.disconnect(); // 접속 끊기
              return result;
          }
          catch (IOException e){
              System.out.println("IO Exception : " + e.getMessage());
          }
      }
  }
  return result;  
 }

ftp 접속 파일 삭제

public static int delete(String localFilePath, String remoteFilePath, String fileName, HttpServletRequest request) throws Exception {
  
  FTPClient ftp = null; // FTP Client 객체
  FileInputStream fis = null; // File Input Stream
  
  String url  = PropertiesHandler.getValue("FTP_URL");  
  String id  = PropertiesHandler.getValue("FTP_ID");
  String pwd  = PropertiesHandler.getValue("FTP_PWD"); 
  String port = PropertiesHandler.getValue("FTP_PORT");
  
  int result = -1;
  try{          
      ftp = new FTPClient(); // FTP Client 객체 생성
      ftp.setControlEncoding("UTF-8"); // 문자 코드를 UTF-8로 인코딩
      ftp.connect(url, Integer.parseInt(port)); // 서버접속 " "안에 서버 주소 입력 또는 "서버주소", 포트번호
      ftp.login(id, pwd); // FTP 로그인 ID, PASSWORLD 입력
      ftp.enterLocalPassiveMode(); // Passive Mode 접속일때 
      ftp.changeWorkingDirectory(remoteFilePath); // 작업 디렉토리 변경
      ftp.setFileType(FTP.BINARY_FILE_TYPE); // 업로드 파일 타입 셋팅
      
      try{          
          boolean isSuccess = ftp.deleteFile(fileName);//파일삭제
          
          if (isSuccess){
     result = 1; // 성공     
    }
    else{
     throw new CommonException("파일을 삭제 할 수 없습니다.");
    }
      } catch(IOException ex){
          System.out.println("IO Exception : " + ex.getMessage());
      }finally{
          if (fis != null){
              try{
                  fis.close(); // Stream 닫기
                  return result;
                  
              }
              catch(IOException ex){
                  System.out.println("IO Exception : " + ex.getMessage());
              }
          }
      }
      ftp.logout(); // FTP Log Out
  }catch(IOException e){
      System.out.println("IO:"+e.getMessage());
  }finally{
      if (ftp != null && ftp.isConnected()){
          try{
              ftp.disconnect(); // 접속 끊기
              return result;
          }
          catch (IOException e){
              System.out.println("IO Exception : " + e.getMessage());
          }
      }
  }
  return result;  
 }
반응형

'Java' 카테고리의 다른 글

[java, javascript] 브라우저 화면 캡처  (2) 2017.01.09
파일 다운로드 한글 깨짐  (3) 2012.10.27