Use FtpClient to create directory if it doesn’t exist.

Apache Common Net package is really easy to use.

Recently, I was using the FtpClient to upload local images to the ftp server.  I’d like to post my uploader here.

package com.oceania.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import com.oceania.modle.FtpServer;
import com.oceania.modle.Img;
public class Uploader {
static FTPClient ftpClient;
private static final Logger logger = Logger.getLogger(Uploader.class);
public static boolean uploadImg(Img img, FtpServer ftp){
boolean returnValue = false;
ftpClient = new FTPClient();
try {
int reply;
if( ftp.getPort() == 0){
           ftpClient.connect(ftp.getHost());
}else{
ftpClient.connect(ftp.getHost(),ftp.getPort());
}
ftpClient.login(ftp.getUser(), ftp.getPassword());
reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
                logger.info(“FTP SERVER REFUSED CONNECTION.”);
                return returnValue;
            }
            FileInputStream fis =  new FileInputStream(img.getLocalPath());
            if ( !ftpClient.changeWorkingDirectory(ftp.getDir())) {
            ftpClient.makeDirectory(ftp.getDir());
            ftpClient.changeWorkingDirectory(ftp.getDir());
            }
            ftpClient.storeFile(img.getName(), fis);
            fis.close();
            ftpClient.logout();
            returnValue = true;
    } catch (SocketException e) {
           e.printStackTrace();
    } catch (IOException e) {
           e.printStackTrace();
     }finally {
           if (ftpClient.isConnected()) {
               try {
                ftpClient.disconnect();
               } catch (IOException ioe) {
               }
           }
       }
return returnValue;
}
}

 

The following two tabs change content below.

silentred

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>