主要要使用到common-net-3.6jar的包
package cn.com.burgeon.serviceclients.liuba.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
/**
* 创建登录FTP服务器
* */
public class FtpConnect {
/**
* 上传文件到FTP
* @param ftpUrl FTP链接
* @param userName 用户名
* @param password 密码
* @param directory 上传目录
* @param srcFile 上传源文件
* @param destName 保存文件名
* */
public static boolean upload(String ftpUrl, String userName,String password,File srcFile,String destName,String path) throws IOException {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
boolean result = false;
try {
ftpClient.connect(ftpUrl);
result = ftpClient.login(userName, password);
ftpClient.enterLocalPassiveMode();
fis = new FileInputStream(srcFile);
//更改上传目录
ftpClient.changeWorkingDirectory(path);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
result = ftpClient.storeFile(destName, fis);
ftpClient.logout(); //文件上传完毕,退出登录
return result;
} catch (NumberFormatException e) {
System.out.println("FTP端口配置错误:不是数字:");
throw e;
} catch (FileNotFoundException e) {
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
try {
if(fis!=null){
fis.close();
}
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
}