package com.zuidaima.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import cn.hutool.core.date.DateUtil;
import cn.hutool.log.StaticLog;
public class FtpUtil {
public static boolean uploadFile(String host, String fileName) {
return uploadFile(host, PropsUtil.getPort(), PropsUtil.getUserName(), PropsUtil.getPassword(),
PropsUtil.getBasePath(), "", fileName);
}
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String fileName) {
boolean result = false;
boolean isReName = PropsUtil.getBooleanValByProps(PropsUtil.IS_RENAME);
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.setControlEncoding(PropsUtil.getChartSet());
ftp.connect(host, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
StaticLog.info("连接FTP失败");
ftp.disconnect();
return result;
}
// 设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// 切换到上传目录
ftp.changeWorkingDirectory(basePath);
ftp.enterLocalPassiveMode();
File file = new File(fileName);
FileInputStream inStream = new FileInputStream(file);
String newName = "";
if (file.getName().toLowerCase().startsWith("d")) {
newName = file.getName();
} else {
if (isReName) {
newName = DateUtil.format(DateUtil.date(), PropsUtil.props.getStr(PropsUtil.FILE_SUFFIX)) + "_"
+ file.getName();
} else {
newName = file.getName();
}
}
// 上传文件
if (!ftp.storeFile(newName, inStream)) {
StaticLog.info("上传{}失败", newName);
inStream.close();
return result;
}
inStream.close();
ftp.logout();
result = true;
StaticLog.info("上传ftp://{}成功,文件名{}", host, newName);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return result;
}
}