티스토리 뷰

IT/JAVA

[JAVA]FTP 파일 업로드 하기

Kanzler 2016. 11. 10. 07:00

클라이언트 혹은 서버를 개발 하다보면 특정서버에 파일을 전송 해야 할 때가 있습니다. 이럴때 사용 하는 것이 바로 FTP(File Transfer Protocol)입니다. 

파일 전송 프로토콜(File Transfer Protocol, FTP)은 TCP/IP 프로토콜을 가지고 서버와 클라이언트 사이의 파일 전송을 하기 위한 프로토콜로 파일 전송 시 유용하게 이용되는 프로토콜입니다. 이번 포스팅에서는 이 FTP를 이용해 파일을 업로드 하는 코드에 대해서 알아 보도록 하겠습니다. 소스 코드를 실핼 하기 위해서는 commons-net-X.X.jar를 이용하기 때문에 사전에 미리 다운로드 받아 프로젝트에 임포트 되어 있어야 합니다.


FtpClient class


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Properties;
 
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
 
public class FtpClient {
 
    private String svrIp;
    private String user;
    private String passwd;
    private String defaultPath;
    
    public FtpClient() {
    }
    
    public FtpClient(String svrIp, String user, String passwd, String defaultPath) {
        this.svrIp = svrIp;
        this.user = user;
        this.passwd = passwd;
        this.defaultPath = defaultPath;
    }
    
    public void init(Properties p) {
        svrIp = p.getProperty("server_ip");
        user = p.getProperty("user_name");
        passwd = p.getProperty("password");
        defaultPath = p.getProperty("default_path");
    }
    
    /**
     * 파일 업로드
     * @param org 원본파일
     * @param targetFile 저장할 파일위치/파일명
     * @throws IOException 
     * @throws SocketException 
     */
    public boolean upload(File org, String targetFile)
            throws SocketException, IOException, Exception {
        
        FileInputStream fis = null;
        
        org.apache.commons.net.ftp.FTPClient clnt = new org.apache.commons.net.ftp.FTPClient();
        clnt.setControlEncoding("utf-8");
        
        try {
            clnt.connect(svrIp);
            //clnt.setBufferSize(1024*1024);
            int reply = clnt.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new Exception("ftp connection refused");
            }
            
            clnt.setSoTimeout(1000 * 10);
            clnt.login(user, passwd);
            clnt.setFileType(FTP.BINARY_FILE_TYPE);
            
            
            clnt.enterLocalActiveMode();
            
            //clnt.enterLocalPassiveMode();
            //clnt.changeWorkingDirectory(defaultPath);
            //clnt.makeDirectory("");
            
            fis = new FileInputStream(org);
            return clnt.storeFile(targetFile, fis);
        } finally {
            if (clnt.isConnected()) {
                clnt.disconnect();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
}
 
cs

사용 방법


1
2
3
4
5
6
7
8
//파일 선언   
File target =null;
 
//저장할 파일을 target에 넣은 부분은 생략(각자 환경에 맞게 파일을 읽어서 넣어주시면 됩니다.)
 
FtpClient ftp_ivr = new FtpClient("FTP 전송할 서버 주소""FTP아이디""FTP비밀번호""");                
boolean result = ftp_ivr.upload(target, "파일 저장 경로"))
System.out.println("FTP result : " + result);
cs



FTP로 전송을 하고 그 결과를 리턴 해주는 간단한 FTP 전송 코드 입니다.

댓글