FTP 파일업로드

FTP 파일업로드

이번에는 자바에서 FTP서버로 파일을 업로드하는 방법을 포스팅해보겠습니다.

먼저 FTP와 접속하기 위해서는 FTPClient가 필요합니다.

직접 다운로드 받으시려면 http://jakarta.apache.org/site/downloads/downloads_commons-net.cgi
위 링크에서 다운받으신 후 라이브러리에 추가해주시면 됩니다.

maven프로젝트일 경우는

1
2
3
4
5
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>

gradle프로젝트일 경우는

1
compile group: 'commons-net', name: 'commons-net', version: '3.6'

버전은 원하시는 버전을 하셔도 상관없습니다.

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
public class className {
private final String server = "server IP";
private int port = port Number;
private final String user = "userId";
private final String pw = "password";
public void ftpTest(..,..,..) throws Throwable {
//받는 변수는 request를 보낸 것에 맞게 받으시면 됩니다.
//웹에서 받은 MultipartFile을 File로 변환시켜줍니다.
File convertFile = new File(fileName);
convertFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convertFile);
fos.write(uploadFile.get(0).getBytes());
fos.close();
try {
//FTPClient를 생성합니다.
FTPClient ftp = new FTPClient();
FileInputStream fis = null
try {
//원하시는 인코딩 타입
ftp.setControlEncoding("utf-8");
ftp.connect(server,port);
ftp.login(user,pw);
//원하시는 파일 타입
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
//제대로 연결이 안댔을 경우 ftp접속을 끊습니다.
if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
}
//파일을 넣을 디렉토리를 설정해줍니다.
//makeDirectory는 directory 생성이 필요할 때만 해주시면 됩니다.
ftp.makeDirectory(directoryRoot);
ftp.changeWorkingDirectory(directoryRoot);
//그 후 이전에 File로 변환한 업로드파일을 읽어 FTP로 전송합니다.
fis = new FileInputStream(convertFile);
isSuccess = ftp.storeFile(fileName, fis);
//storeFile Method는 파일 송신결과를 boolean값으로 리턴합니다
if(isSuccess) {
System.out.println("업로드 성공");
} else {
System.out.println("업로드 실패");
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(fis!=null) {
try {
fis.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(ftp!=null && ftp.isConnected()) {
try {
ftp.disconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
}

이렇게 해서 FTP업로드 로직을 포스팅해봤습니다.
여기서 주의할 점은 FTPClient의 생성입니다.
저는 처음에 전역변수로 FTPClient를 선언해주었는데 이렇게 되면,
FTP로 송신 중 다른 FTP요청이 들어오면 작업중인 연결이 끊어지게 됩니다.
그런것을 방지하기 위하여 요청때마다 메소드안에서 FTPClient를 생성하여
FTPClient를 중복사용 하지 않게 방지할 수 있습니다.

Share