티스토리 뷰

CodeJava.net 에 샘플이 있어서 응용해 봤는데 쉽게 구현이 되었다. 다음에 다시 구현할 일이 있으면 그대로 베껴 쓰기 위해 스크랩해 둔다. 


import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

  

 

         /* 일반 FTP 방식으로 파일을 다운로드 함

          *

          */

    private  void downloadFile(String downloadFileName ) {

        String server = CommonCode.REMOTE_HOST_NAME;

        int port = 21;

        String user = CommonCode.FTP_USER_NAME;

        String pass = CommonCode.FTP_PASSWORD;

 

        FTPClient ftpClient = new FTPClient();

        try {

 

            ftpClient.connect(server, port);

            ftpClient.login(user, pass);

            ftpClient.enterLocalPassiveMode();

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

 

            // APPROACH #1: using retrieveFile(String, OutputStream)

            String remoteFile1 =  CommonCode.REMOTE_PATH + downloadFileName;

            File downloadFile1 = new File(CommonCode.LOCAL_PATH + downloadFileName);

            OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));

            boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);

            outputStream1.close();

 

            if (success) {

                logger.debug("File #1 has been downloaded successfully.");

            }

 

            /*

            // APPROACH #2: using InputStream retrieveFileStream(String)

            String remoteFile2 = CommonCode.REMOTE_PATH + downloadFileName;

            File downloadFile2 = new File(CommonCode.LOCAL_PATH + downloadFileName);

            OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));

            InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);

            byte[] bytesArray = new byte[4096];

            int bytesRead = -1;

            while ((bytesRead = inputStream.read(bytesArray)) != -1) {

                outputStream2.write(bytesArray, 0, bytesRead);

            }

 

            success = ftpClient.completePendingCommand();

            if (success) {

                System.out.println("File #2 has been downloaded successfully.");

            }

            outputStream2.close();

            inputStream.close();

                           */

        } catch (IOException ex) {

            logger.error("Error: " + ex.getMessage());

            ex.printStackTrace();

        } finally {

            try {

                if (ftpClient.isConnected()) {

                    ftpClient.logout();

                    ftpClient.disconnect();

                }

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        }

    }

 

         /* 일반 FTP 방식으로 파일을 업로드 함

          *

          */

    private void uploadFile(String uploadFileName) {

        String server = CommonCode.REMOTE_HOST_NAME;

        int port = 21;

        String user = CommonCode.FTP_USER_NAME;

        String pass = CommonCode.FTP_PASSWORD;

 

        FTPClient ftpClient = new FTPClient();

        try {

 

            ftpClient.connect(server, port);

            ftpClient.login(user, pass);

            ftpClient.enterLocalPassiveMode();

 

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

 

            // APPROACH #1: uploads first file using an InputStream

            File firstLocalFile = new File(CommonCode.LOCAL_PATH + uploadFileName );

 

            String firstRemoteFile = uploadFileName;

            InputStream inputStream = new FileInputStream(firstLocalFile);

 

            logger.debug("Start uploading first file");

            boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);

            inputStream.close();

            if (done) {

                logger.debug("The first file is uploaded successfully.");

            }

 

            /*

            // APPROACH #2: uploads second file using an OutputStream

            File secondLocalFile = new File(CommonCode.LOCAL_PATH + uploadFileName);

            String secondRemoteFile = CommonCode.REMOTE_HOST_NAME + uploadFileName;

            inputStream = new FileInputStream(secondLocalFile);

 

            logger.debug("Start uploading second file");

            OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);

            byte[] bytesIn = new byte[4096];

            int read = 0;

 

            while ((read = inputStream.read(bytesIn)) != -1) {

                outputStream.write(bytesIn, 0, read);

            }

            inputStream.close();

            outputStream.close();

 

            boolean completed = ftpClient.completePendingCommand();

            if (completed) {

                logger.debug("The second file is uploaded successfully.");

            }

            */

 

        } catch (IOException ex) {

            logger.error("Error: " + ex.getMessage());

            ex.printStackTrace();

        } finally {

            try {

                if (ftpClient.isConnected()) {

                    ftpClient.logout();

                    ftpClient.disconnect();

                }

            } catch (IOException ex) {

                ex.printStackTrace();

            }

        }

    }




신고
댓글
  • 프로필사진 fromBusan 샘플 감사합니다. 올려주신 샘플 참조해서 잘 되긴 하는데 몇가지 질문이 있네요~~
    1)CommonCode 클래스는 어떻게 생겼는지 좀 볼 수 있을까요?
    2)그리고 LOCAL_PATH 는 클라이언트PC 에서 선택된 파일의 전체경로인가요? 크롬브라우저에서는 fakepath 같이 encoded path로 가져와서 어떻게 가져올 수 있는지도 혹시나 알고 계신다면 좀 알려주심 감사요~~ㅎ
    멀리서 고생많으십니다~~
    Take goooood care N happy new year!
    2017.01.02 16:32 신고
댓글쓰기 폼