用common-net-ftp上传文件

本文介绍了一个简单的FTP文件上传工具类,支持指定主机、端口、用户名、密码等参数,并能将文件上传到指定路径。该工具类使用Apache Commons Net库实现。

这个是上传文件的工具类,也很简单

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

/**
 *
 * @author lan
 */
public final class FTPUtil {

    private static final Log log = LogFactory.getLog(FTPUtil.class);

    public static boolean upload(String host, int port, String user, String pwd, String targetPath, String name, InputStream is) {
        if (name == null || is == null) {
            return false;
        }
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(host, port);
            ftp.login(user, pwd);
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                log.warn("ftp login failed");
                return false;
            }
            if (targetPath != null) {//验证是否有该文件夹,有就转到,没有创建后转到该目录下
                if (!ftp.changeWorkingDirectory(targetPath)) {
                    ftp.makeDirectory(targetPath);
                    ftp.changeWorkingDirectory(targetPath);
                }
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//关键,必加,否则按照默认的ascii上传,会出现文件损坏的现象
            ftp.storeFile(name, is);
            is.close();
            ftp.logout();
            log.info("upload " + name + " success");
            return true;
        } catch (SocketException ex) {
            log.error(ex.getMessage(), ex);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ex) {
                    log.error(ex.getMessage(), ex);
                }
            }
        }
        return false;
    }

    public static boolean upload(String host, int port, String user, String pwd, String targetPath, File f) {
        InputStream is = null;
        try {
            is = new FileInputStream(f);
        } catch (FileNotFoundException ex) {
            log.error(ex.getMessage(), ex);
        }
        return upload(host, port, user, pwd, targetPath, f.getName(), is);
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值