package cn.gzsxt.base.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FtpUtils {
FTPClient client = null;
/**
* 文件上传
* @param hostName ftp主机名
* @param port ftp主机端口
* @param username 上传用户名
* @param password 上传用户密码
* @param basePath 上传基础路径
* @param filePath 文件存放路径
* @param remoteFileName 上传后文件名称
* @param in 文件输入流
* @return
*/
public static boolean upload(String hostName,int port,String username,String password,String basePath,
String filePath,String remoteFileName,InputStream in){
//1、创建客户端
FTPClient client = new FTPClient();
try {
//2、建立和服务端的链接
client.connect(hostName, port);
//3、登陆服务端
client.login(username, password);
//4、指定图片上传的方式为二进制,即字节流
client.setFileType(FTP.BINARY_FILE_TYPE);
//5、指定上传的访问模式为被动模式 说明:大部分的操作系统,默认的都是被动模式,并且禁用了主动了模式
client.enterLocalPassiveMode();
//6、指定上传的目录 默认目录 是当前ftpuser用户的家目录
boolean flag = client.changeWorkingDirectory(basePath+filePath);
//如果切换目录失败,则创建指定的目录
if(!flag){
//创建目录失败,则可能是存在没有创建的父目录
if(!client.makeDirectory(basePath+filePath)){
String tempPath = basePath;
String[] split = filePath.split("/");
for (String string : split) {
if(null!=string && !"".equals(string)){
tempPath = tempPath+"/"+string;
//先判断第一层路径是否存在,如果不存在,则创建
if(!client.changeWorkingDirectory(tempPath)){
//如果创建第一层路径成功,则判断是否能切换到这一层路径
if(client.makeDirectory(tempPath)){
//切换失败,则返回false
if(!client.changeWorkingDirectory(tempPath)){
return false;
}
//如果创建第一层路径失败,则直接返回false
}else{
return false;
}
}
//如果有空路径,则直接跳过
}else{
continue;
}
}
}else{
//创建成功,则直接切换到指定的目录
if(!client.changeWorkingDirectory(basePath+filePath)){
return false;
}
}
}
//8、上传
boolean result = client.storeFile(remoteFileName, in);
return result;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally {
//9,退出登录,并关闭连接
try {
if(client.logout()){
client.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}