Developers

Java ftpClient 사용한 ftp 전송 구현

오페투오소 2016. 12. 8. 09:28

org.apache.commons.net.ftp.FTPClient



파일업로드 ftp 구현은 




1. web -> server MultipartRequest 방식으로 올리고


2. server에서 받아온 file을 서버에 저장 


3. 저장한 파일을 ftp 전송(파일서버에 전송)


4. server에 저장된 tmp 파일 제거 



디렉토리는 1step 씩 생성되며 


디렉토리가 없으면 ftp 전송이 안됨 ( 없는 디렉토리 생성 x )


디렉토리 있는지 검사 하는 함수가 없어 ,

디렉토리 이동을 해서 성공하면 디렉토리가 있는것이고 

실패 하면 디렉토리 생성해야됨 


  existed = fm.changeWorkingDirectory(singleDir);

                      if (!existed) { 


디렉토리 생성후 디렉토리 안으로 이동해 줘야 

다음 step 부터 생성됨



FileUpload 


import java.io.File;

import java.io.IOException;

import java.net.UnknownHostException;


import org.springframework.web.multipart.MultipartFile;


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

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

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


public class FileUpload {

private static final String _svr = "1.201.137.64"; //ftp 서버

private static final int _port = 21; //ftp 포트

private static final String _svr_user = "audien";

private static final String _svr_pass = "comsta10454$";

private static FTPManager instance = new FTPManager();

//private static final String[] _war_dst = {"/storage/tomcat-8/instance1/webapps/audien-b2c.war", "/storage/tomcat-8/instance2/webapps/audien-b2c.war", "/storage/tomcat-8/instance3/webapps/audien-b2c.war", "/storage/tomcat-8/instance4/webapps/audien-b2c.war"};

//private static final String _war_src = "C:\\_HUI\\01.dev\\workspace\\gm2\\audien-b2c\\target\\audien-b2c.war";


/*    

type = banner, category, coupon, event

war_dst = /storage/tomcat-8/instance1/webapps/audien-b2c.war //서버에 생성될 파일 경로

war_src = C:\\_HUI\\01.dev\\workspace\\gm2\\audien-b2c\\target\\audien-b2c.war //복사될 파일 경로

*/

private static FTPManager getInstance() {

return instance;

}

public boolean putFile(String file_src, String file_dst, String file_nm) {

boolean ret=false;

FTPManager fm = instance;

try {

fm.open(_svr, 21, _svr_user, _svr_pass);

System.out.println("replay=" + fm.getReplyString());


fm.setFileType(FTPManager.BINARY_FILE_TYPE);


System.out.println("replay=" + fm.getReplyString());

fm.changeWorkingDirectory("/");

System.out.println("Current Directory = "+ fm.printWorkingDirectory());

 String[] pathElements = file_dst.split("/");

              if (pathElements != null && pathElements.length > 0) {

             boolean existed;

                  for (String singleDir : pathElements) {

                 existed = fm.changeWorkingDirectory(singleDir);

                      if (!existed) {

                          boolean created = fm.makeDirectory(singleDir);

                          if (created) {

                              System.out.println("CREATED directory: " + singleDir);

                              fm.changeWorkingDirectory(fm.printWorkingDirectory()+"/"+singleDir);

                          } else {

                              System.out.println("COULD NOT create directory: " + singleDir);

                          }

                      }

                  }

              }

              

            

              System.out.println("upload ["+file_src+" to "+_svr + fm.printWorkingDirectory()+file_nm+"]");

if (fm.putFile(file_src, fm.printWorkingDirectory()+"/"+file_nm)) {

System.out.println("successfully");

ret = true;

} else {

System.out.println("File Upload Failure");

ret = false;

}

fm.close();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

//System.exit(0);

return ret;

}

public String getFilePath() {

String filePath = this.getClass().getResource("").getPath(); 

filePath = filePath.substring(1,filePath.indexOf(".metadata"))+"audien-b2c-mgmt/";

        

return filePath+"src/main/webapp/resources/files/tmp/";

}

public String getFtpPath(String type, String path) {

String filePath= "/storage/common/images/"+type+"/";

  filePath= filePath+path.substring(0,1)+"/"

+path.substring(1,3)+"/"

+path.substring(3,5)+"/"

+path.substring(5,7)+"/";

//+path.substring(7,9)+"/";

  

return filePath;

}


public void removeFile(String file_src){

File file = new File(file_src);

       

        if(file.exists()){

            file.delete();

        }

}

public String getExtension(String fName){

String extension = "";

if( fName != null ) {

String strSplit[] = fName.split("[.]");

if( strSplit.length >= 2 ) {

extension = "." + strSplit[strSplit.length-1];

}

}

return extension;

}

}

 


FTPManager 



import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.net.SocketException;

import java.net.UnknownHostException;


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

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

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



public class FTPManager extends FTPClient {


private static String UNIX_FILE_SEP = StringUtil.UNIX_FILE_SEP;


private static char EXTENSION_SEP = StringUtil.EXTENSION_SEP;


private static String FILE_SEP = StringUtil.FILE_SEP;


private static String REFUSE_CONNECTION = "FTP server refused connection.";


private static String FAIL_LOGIN = "Unknown username and password.";


private static String FAIL_LOGOUT = "Unknown error caused by FTP server.";


private static String UNKNOWN_FILE = "Unknown file name and extension.";


private static String NOT_FOUND_FILE = "Given file does not exist.";

private static String UNKNOWN_ABS_FILE = "No absolute path file.";


private static String UNKNOWN_DIR = "Given directory does not exist.";


private static String ALREADY_FILE = "Already exists file name.";


public FTPManager() {


}


public void open(String server, int port, String user, String password)

throws SocketException, IOException {

try {

int reply;


FTPClientConfig conf = null;


conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);


configure(conf);

connect(server, port);


//System.out.println("Connected to " + server + ".");

//System.out.print(getReplyString());


// After connection attempt, you should check the reply code to

// verify success.

reply = getReplyCode();


if (!FTPReply.isPositiveCompletion(reply)) {

disconnect();

throw new SocketException(REFUSE_CONNECTION);

}


if (!login(user, password))

throw new SocketException(FAIL_LOGIN);


} catch (SocketException e) {

throw e;

} catch (IOException e) {

throw e;

}

}


public void close() throws IOException, SocketException {

try {

if (isConnected()) {

if (!logout()) {

throw new SocketException(FAIL_LOGOUT);

}


disconnect();


}

} catch (IOException e) {

throw e;

}


}


public boolean getFile(String localfile) throws IOException,

FileNotFoundException {


DataOutputStream dos = null;

try {

File f = new File(localfile);

if (f.exists()) {

throw new FileNotFoundException(ALREADY_FILE);

}

dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));

return retrieveFile(new StringBuffer().append(

printWorkingDirectory()).append(UNIX_FILE_SEP).append(

f.getName()).toString(), dos);

} catch (FileNotFoundException e) {

throw e;

} catch (IOException e) {

throw e;

} finally {

try {

if (dos != null)

dos.close();

} catch (IOException e) {

throw e;

}

}

}


public boolean getFile(String localfile, String remotefile)

throws IOException, FileNotFoundException, IllegalArgumentException {


if (remotefile == null || remotefile.length() == 0

|| remotefile.indexOf(EXTENSION_SEP) == -1) {

throw new FileNotFoundException(UNKNOWN_FILE);

}


int n = remotefile.lastIndexOf(UNIX_FILE_SEP);

if (n == -1) {

throw new IOException(UNKNOWN_ABS_FILE);

}


// check whether remotefile exists

String cur_dir = remotefile.substring(0, n);

String[] files = listNames(cur_dir);


if (files == null) {

throw new IllegalArgumentException(UNKNOWN_DIR);

}


int len = files.length;

boolean b = false;

for (int i = 0; i < len; i++) {

// System.out.println("file name=" + files[i]);

if (files[i].equals(remotefile)) {

b = true;

break;

}

}

// not found remote file

if (!b) {

throw new FileNotFoundException(NOT_FOUND_FILE);

}


DataOutputStream dos = null;

try {

File f = new File(localfile);

if (f.exists()) {

throw new FileNotFoundException(ALREADY_FILE);

}

dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f)));

return retrieveFile(remotefile, dos);

} catch (FileNotFoundException e) {

throw e;

} catch (IOException e) {

throw e;

} finally {

try {

if (dos != null)

dos.close();

} catch (IOException e) {

throw e;

}

}

}


public boolean putFile(String localfile) throws IOException,

FileNotFoundException {

try {

return putFile(localfile, localfile.substring(localfile.lastIndexOf(FILE_SEP) + 1));

} catch (FileNotFoundException e) {

throw e;

} catch (IOException e) {

throw e;

}


}


public boolean putFile(String localfile, String remotefile)

throws IOException, FileNotFoundException {


if (remotefile == null || remotefile.length() == 0

|| remotefile.indexOf(EXTENSION_SEP) == -1) {

throw new FileNotFoundException(UNKNOWN_FILE);

}


DataInputStream dis = null;

String cur_dir;

try {


// check whether only file

if (remotefile.indexOf(UNIX_FILE_SEP) == -1) {

cur_dir = printWorkingDirectory();


remotefile = new StringBuffer().append(cur_dir).append(

UNIX_FILE_SEP).append(remotefile).toString();

} else {

// check with listNames function

cur_dir = remotefile.substring(0, remotefile.lastIndexOf(UNIX_FILE_SEP));

}


// not supported. ==> "list" command

// FTPFile[] files = listFiles(cur_dir);

// int len = files.length;

// System.out.println("file length="+ len);

//

// for (int i=0; i< len;i++ ) {

// System.out.println("file name="+ files[i].getName());

// //System.out.println("Already exists file name.");

// }

String[] files = listNames(cur_dir);

if (files != null) {

int len = files.length;

for (int i = 0; i < len; i++) {

// System.out.println("file name=" + files[i]);

if (files[i].equals(remotefile)) {

throw new IOException(ALREADY_FILE);

}

}

}

dis = new DataInputStream(new BufferedInputStream(new FileInputStream(localfile)));

return appendFile(remotefile, dis);


} catch (FileNotFoundException e) {

throw e;

} catch (IOException e) {

throw e;

} finally {

try {

if (dis != null)

dis.close();

} catch (IOException e) {

throw e;

}

}

}


public boolean renameFile(String oldname, String newname)

throws IOException, IllegalArgumentException, FileNotFoundException {


if (oldname == null || oldname.length() == 0

|| oldname.indexOf(EXTENSION_SEP) == -1) {

throw new FileNotFoundException(UNKNOWN_FILE);

}


if (newname == null || newname.length() == 0

|| newname.indexOf(EXTENSION_SEP) == -1) {

throw new FileNotFoundException(UNKNOWN_FILE);

}


try {


// check whether only file

if (oldname.indexOf(UNIX_FILE_SEP) == -1) {

String cur_dir = printWorkingDirectory();


// change to absolute path file.

oldname = new StringBuffer().append(cur_dir).append(

UNIX_FILE_SEP).append(oldname).toString();


// check whether file exists with listNames function

String[] files = listNames(cur_dir);


// don't need to check because of using printWorkingDirectory

// function.

// if (files == null) {

// throw new IllegalArgumentException(UNKNOWN_DIR);

// }


boolean b = false;


int len = files.length;

for (int i = 0; i < len; i++) {

// System.out.println("file name=" + files[i]);

if (files[i].equals(oldname)) {

b = true;

break;

}

}


// not found original file

if (!b) {

throw new IllegalArgumentException(NOT_FOUND_FILE);

}


return rename(oldname, newname);


} else { // file contains directory

// check with listNames function

String cur_dir = oldname.substring(0, oldname

.lastIndexOf(UNIX_FILE_SEP));

String[] files = listNames(cur_dir);


if (files == null) {

throw new IllegalArgumentException(UNKNOWN_DIR);

}


int len = files.length;

boolean b = false;

for (int i = 0; i < len; i++) {

// System.out.println("file name=" + files[i]);

if (files[i].equals(oldname)) {

b = true;

break;

}

}


// not found original file

if (!b) {

throw new FileNotFoundException(NOT_FOUND_FILE);

}


return rename(oldname, newname);

}


} catch (IOException e) {

throw e;

}

}


public boolean uploadFile(String localfile, String remotefile)

throws IOException, FileNotFoundException {


if (remotefile == null || remotefile.length() == 0

|| remotefile.indexOf(EXTENSION_SEP) == -1) {

throw new FileNotFoundException(UNKNOWN_FILE);

}


FileInputStream fis = null;

String cur_dir;

try {

// if (FTP.STREAM_TRANSFER_MODE) {


// check whether only file

if (remotefile.indexOf(UNIX_FILE_SEP) == -1) {

cur_dir = printWorkingDirectory();

remotefile = new StringBuffer().append(cur_dir).append(

UNIX_FILE_SEP).append(remotefile).toString();

} else {

cur_dir = remotefile.substring(0, remotefile

.lastIndexOf(UNIX_FILE_SEP));

}


// compare file size between localfile and remotefile

long remotesize = getRemoteFileSize(remotefile);

// long localsize = getLocalFileSize(localfile);

if (remotesize == 0) {

fis = new FileInputStream(localfile);

} else {

fis = new FileInputStream(localfile);

fis.skip(remotesize);

}


return appendFile(remotefile, fis);

// }


} catch (FileNotFoundException e) {

throw e;

} catch (IOException e) {

throw e;

} finally {

try {

if (fis != null)

fis.close();

} catch (IOException e) {

throw e;

}

}

}


public long getRemoteFileSize(String remotefile) throws IOException {


try {

int ret = sendCommand("SIZE", remotefile);


String reply = getReplyString().trim();

if (ret != 213) {

return 0L;

}

return Long.parseLong(reply.substring(4));


} catch (IOException e) {

throw e;

}

}


public String getFileTimeStamp(String remotefile)

throws FileNotFoundException, IOException {


if (remotefile == null || remotefile.length() == 0

|| remotefile.indexOf(EXTENSION_SEP) == -1) {

throw new FileNotFoundException(UNKNOWN_FILE);

}


try {


int ret = sendCommand("MDTM", remotefile);

String reply = getReplyString().trim();

if (ret != 213) {

throw new IOException(reply);

}


return reply.substring(4);

} catch (IOException e) {

throw e;

}

}


public long getLocalFileSize(String localfile) throws FileNotFoundException {


File f = new File(localfile);


if (!f.exists()) {

throw new FileNotFoundException(NOT_FOUND_FILE);

}


if (!f.isFile()) {

throw new FileNotFoundException(NOT_FOUND_FILE);

}


return f.length();

}


public static void main(String args[]) {


FTPManager fm = new FTPManager();

try {

// ---------------------------------------------

// Test for upload file

// ---------------------------------------------

fm.open("192.168.0.34", 21, "srbt", "Nam7728");


System.out.println("replay=" + fm.getReplyString());


fm.setFileType(FTPManager.BINARY_FILE_TYPE);


System.out.println("replay=" + fm.getReplyString());


// streaming file is ok

// fm.uploadFile("C:\\Temp\\aaa.mpg","/app1/srbt/tmp/aaa.mpg");

// fm.uploadFile("C:\\Temp\\bbb.pdf","/app1/srbt/tmp/bbb.pdf");


// long size = fm.getRemoteFileSize("/app1/srbt/tmp/aaa.mpg");

// System.out.println("size=" + size);

//

// String date = fm.getFileTimeStamp("/app1/srbt/tmp/aaa.mpg");

// System.out.println("replay=" + fm.getReplyString());

// System.out.println(date);

//

// size = fm.getLocalFileSize("C:\\Temp\\aaa.mpg");

// System.out.println(size);


// --------------------------------------------

// Test for unix server

// --------------------------------------------

// String localfile = "C:\\Temp\\alaw.wav";

// String remotefile = "test.wav";

// fm.open("192.168.0.34", 21, "srbt", "Nam7728");

// fm.setFileType(FTPManager.BINARY_FILE_TYPE);

//

// System.out.println("Current Directory = "

// + fm.printWorkingDirectory());

//

// if (fm.changeWorkingDirectory("tmp")) {

// System.out.println("ChangeDir Success = "

// + fm.printWorkingDirectory());

// } else {

// System.out.println("ChangeDir Failure");

// }

//

// if (fm.putFile(localfile, remotefile)) {

// System.out.println("File Upload Success");

// } else {

// System.out.println("File Upload Failure");

// }

//

// remotefile = "/app1/srbt/tmp/test1.wav";

// if (fm.putFile(localfile, remotefile)) {

// System.out.println("File Upload Success");

// } else {

// System.out.println("File Upload Failure");

// }

//

// if (fm.putFile(localfile)) {

// System.out.println("File Upload Success");

// } else {

// System.out.println("File Upload Failure");

// }

//

// if (fm.renameFile(remotefile, "aaa.wav")) {

// System.out.println("File Rename Success");

// } else {

// System.out.println("File Rename Failure");

// }

//

// if (fm.renameFile(remotefile, "aaa.wav")) { // test for existing

// System.out.println("File Rename Success");

// } else {

// System.out.println("File Rename Failure");

// }

//

// if (fm.getFile("c:\\aaa.wav")) {

// System.out.println("File Download Success");

// } else {

// System.out.println("File Download Failure");

// }

//

// if (fm.getFile("c:\\aaa1.wav", "/app1/srbt/tmp/test.wav")) {

// System.out.println("File Download Success");

// } else {

// System.out.println("File Download Failure");

// }


// --------------------------------------------

// Test for NT server

// --------------------------------------------

// String localfile = "C:\\Temp\\alaw.wav";

// String remotefile = "test.wav";

//

// fm.open("192.168.6.97", 21, "srbt", "Nam7728");

// System.out.println(fm.getSystemName());

// fm.setFileType(FTPManager.BINARY_FILE_TYPE);

// fm.type(FTPManager.BINARY_FILE_TYPE);

//

// System.out.println("Current Directory = "

// + fm.printWorkingDirectory());

//

// if (fm.changeWorkingDirectory("tmp")) {

// System.out.println("ChangeDir Success = "

// + fm.printWorkingDirectory());

// } else {

// System.out.println("ChangeDir Failure");

// }

//

// if (fm.putFile(localfile, remotefile)) {

// System.out.println("File Upload Success");

// } else {

// System.out.println("File Upload Failure");

// }

//

// remotefile = "/tmp/test1.wav";

// if (fm.putFile(localfile, remotefile)) {

// System.out.println("File Upload Success");

// } else {

// System.out.println("File Upload Failure");

// }

//

// if (fm.putFile(localfile)) {

// System.out.println("File Upload Success");

// } else {

// System.out.println("File Upload Failure");

// }

//

// if (fm.renameFile(remotefile, "aaa.wav")) {

// System.out.println("File Rename Success");

// } else {

// System.out.println("File Rename Failure");

// }

//

// if (fm.getFile("C:\\aaa.wav")) {

// System.out.println("File Download Success");

// } else {

// System.out.println("File Download Failure");

// }

//

// if (fm.getFile("C:\\aaa1.wav", "/tmp/test.wav")) {

// System.out.println("File Download Success");

// } else {

// System.out.println("File Download Failure");

// }


fm.close();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

}


}

}