cn.tncube.util.FtpUtilComponent Maven / Gradle / Ivy
package cn.tncube.util;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.tncube.properties.FtpProperties;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
/**
* @author liuhaomin
* @date 2022/5/10
*/
@Data
@Slf4j
@Component
public class FtpUtilComponent {
@Resource
private FtpProperties ftpProperties;
private boolean connectServer(FTPClient ftpClient){
Boolean isSuccess=false;
try {
ftpClient.connect(ftpProperties.getFtpIp(),ftpProperties.getFtpPort());
isSuccess=ftpClient.login(ftpProperties.getFtpUser(),ftpProperties.getFtpPass());
} catch (IOException e) {
log.error("连接ftp服务器失败 参数 {} 异常{}", ftpProperties.toString(),e);
}
return isSuccess;
}
public boolean uploadFile(String remotePath, List fileList) throws IOException {
boolean upload=true;
FTPClient ftpClient = new FTPClient();
FileInputStream fileInputStream=null;
//connect to ftpServer
if (connectServer(ftpClient)){
try {
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
for (File fileItem:fileList
) {
fileInputStream=new FileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(),fileInputStream);
}
} catch (IOException e) {
log.error("上传文件异常",e);
upload=false;
}finally {
fileInputStream.close();
ftpClient.disconnect();
}
}
return upload;
}
private static String ZN_CHARSET = "GBK";
private static String LOCAL_CHARSET = "GBK";
public boolean uploadToFtp(String remotePath, String fileName, File file) throws IOException {
boolean upload = true;
FTPClient ftpClient = new FTPClient();
//connect to ftpServer
if (connectServer(ftpClient)) {
try {
String newFileName = new String(fileName.getBytes(ZN_CHARSET),ftpProperties.getServerCharset());
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
LOCAL_CHARSET = "UTF-8";
}
ftpClient.setControlEncoding(LOCAL_CHARSET);
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
//上传文件 参数:上传后的文件名,输入流
upload = ftpClient.storeFile(newFileName, new FileInputStream(file));
log.info("{} 文件导入 {} 路径 成功",fileName,remotePath);
} catch (IOException e) {
log.error("{} 文件导入 {} 路径 失败{}",fileName,remotePath,e);
upload = false;
} finally {
ftpClient.disconnect();
}
}
return upload;
}
}