本章实现本地文件夹上传至ftp共享服务器 自动上传
上代码
package com.mes.web.controller.basedata;
import com.mes.common.config.MesConfig;
import com.mes.common.core.domain.AjaxResult;
import com.mes.common.exception.MesException;
import com.mes.system.domain.FileConfig;
import com.mes.system.service.FileConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.util.Password;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @Author: wxc
* @Date: 2022/12/79:47
*/
@Slf4j
@Component
@RestController
@RequestMapping("/downfile")
public class UtilFtpAllFileController {
private FTPClient ftpClient = new FTPClient();
private String strIp;
private int intPort;
private String user;
private String password;
final static Logger logger = LoggerFactory.getLogger(UtilFtpAllFileController.class);
@Autowired
FileConfigService fileConfigService;
@Scheduled(cron = "0 0/10 * * * ?")
//@PostMapping("/file")
public AjaxResult downloadTest() throws IOException, ParseException {
if(MesConfig.getFileEnable().equals("true")) {
//获取ftp服务器配置信息
List<FileConfig> list = fileConfigService.getAll(null);
List<AjaxResult> timeList = new ArrayList<>();
if (list.isEmpty()) {
logger.info("Please add configuration information to the file configuration!");
return AjaxResult.success("请在文件配置中添加配置信息!");
}
System.out.println("文件下载开始……");
logger.info("文件下载开始……");
for (FileConfig fileConfig : list) {
// ftp连接之前先设置字符编码,防止下载后中文名字文件损坏
ftpClient.setControlEncoding("GBK");
ftpClient.connect(fileConfig.getFtpIp(), fileConfig.getFtpPort());
// 登录服务器
ftpClient.login(fileConfig.getFtpUserName(), fileConfig.getFtpPassword());
// 判断返回码是否合法
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
// 不合法时断开连接
ftpClient.disconnect();
// 结束程序
return AjaxResult.error("ftp服务器登陆失败");
}
long systemDate = new SimpleDateFormat("yyyy-MM-dd").parse(date1()).getTime();
System.out.println("Time====================>" + systemDate);
//下载文件夹
long t1 = System.currentTimeMillis();
boolean downLoadFlag = downLoadDirectory(fileConfig.getLocalPath(), fileConfig.getFtpPath(), systemDate);
// 修改抓取到的文件的名字 用不到可以注释调
fileConfigService.putUpdateName();
AjaxResult ajax = new AjaxResult();
if (!downLoadFlag) {
ajax.put("msg", fileConfig.getFtpPath() + "文件下载失败!");
}
long t2 = System.currentTimeMillis();
long t3 = t2 - t1;
ajax.put("msg", fileConfig.getFtpPath() + "下载文件花费" + t3 + "毫秒");
System.out.println(fileConfig.getFtpPath() + "下载文件花费" + t3 + "毫秒");
timeList.add(ajax);
// 登出服务器
ftpClient.logout();
}
logger.info("successful!");
System.out.println("文件下载完成!");
return AjaxResult.success(timeList);
}
return null;
}
/***
* 下载文件
* @param remoteFileName 待下载文件名称
* @param localDires 下载到当地那个路径下
* @param
* */
public boolean downloadFile(String remoteFileName, String localDires, long time, long ftpFileTime) {
//获取文件本地下载路径--D:/ideaSoft/mes/ftpFile/image/文件名
String strFilePath = localDires + "/" + remoteFileName;
File localFile = new File(strFilePath);
BufferedOutputStream outStream = null;
boolean success = false;
if (ftpFileTime >= time) {
try {
//ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(localFile));
logger.info(remoteFileName + "开始下载....");
//小文件下载
success = ftpClient.retrieveFile(remoteFileName, outStream);
if (success) {
logger.info(remoteFileName + "成功下载到" + strFilePath);
System.out.println(remoteFileName + "===============>下载成功!");
return true;
}
} catch (Exception e) {
e.printStackTrace();
logger.error(remoteFileName + "下载失败");
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (!success) {
logger.error(remoteFileName + "下载失败!!!");
}
}
return success;
}
/***
* @下载文件夹
* @param localDirectoryPath 本地地址
* @param remoteDirectory 远程文件夹
* */
public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory, long time) throws MesException {
//获取远程文件夹名字,并创建本地文件夹对象--image
String fileName = new File(remoteDirectory).getName();
//获取本地下载文件夹路径--D:/ideaSoft/mes/ftpFile/image
localDirectoryPath = localDirectoryPath + "/" + fileName;
// 连接至服务器,端口默认为21时,可直接通过URL连接
try {
// 设置ftp文件操作目录--/image
ftpClient.changeWorkingDirectory(remoteDirectory);
ftpClient.enterLocalPassiveMode();
// 设置文件类型,二进制
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 设置缓冲区大小
ftpClient.setBufferSize(3072);
// 构造本地文件夹--D:/ideaSoft/mes/ftpFile/image
File localFilePath = new File(localDirectoryPath);
if (!localFilePath.exists()) {
localFilePath.mkdirs();
System.out.println(localFilePath + "文件夹创建成功!");
}
// 获取文件操作目录下所有文件名称--/image下所有文件
FTPFile[] allFile = ftpClient.listFiles();
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
//判断文件对象是否是文件
if (!allFile[currentFile].isDirectory()) {
//是文件,获取文件名字
String srcName = allFile[currentFile].getName();
// 获取文件创建时间
long ftpFileTime = allFile[currentFile].getTimestamp().getTimeInMillis();
//调用下载文件方法,下载文件到本地对应路径下
downloadFile(srcName, localDirectoryPath, time, ftpFileTime);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
//获取ftp操作目录
String strRemoteDirectoryPath = remoteDirectory + "/" + allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath, strRemoteDirectoryPath, time);
}
}
} catch (IOException e) {
e.printStackTrace();
logger.info("下载文件夹失败");
return false;
}
return true;
}
/* *
* Ftp构造函数
*/
public UtilFtpAllFileController(String strIp, int intPort, String user, String Password) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient = new FTPClient();
}
public UtilFtpAllFileController() {
}
public static String date1() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
return df.format(new Date());// new Date()为获取当前系统时间
}
}