<dependency>
<groupId>commons-netgroupId>
<artifactId>commons-netartifactId>
<version>3.6version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.16.10version>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>4.0.9version>
dependency>
自行添加自己的配置
#ftp配置
#ftp服务器的ip地址
ftp.host=
#ftp服务器的端口号
ftp.port=
#ftp服务器的上传下载路径
ftp.filepath=/
#ftp服务器的用户名
ftp.username=Admin
#ftp服务器的密码
ftp.password=
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
@Component
@Data
@Slf4j
@Service
public class FTPUtils {
public static final int imageCutSize = 300;
@Value("${ftp.username}") //用户名
private String userName;
@Value("${ftp.password}") //密码
private String passWord;
@Value("${ftp.host}") //ip地址
private String ip;
@Value("${ftp.port}") //端口号
private int port;
@Value("${ftp.filepath}")
private String CURRENT_DIR; // 文件存放的目录
public static final String DIRSPLIT = "/";
private String DOWNLOAD_DIR;
private FTPClient ftpClient = new FTPClient();
//上传
public boolean uploadToFtp(InputStream buffIn, String fileName, boolean needDelete)
throws FTPConnectionClosedException, IOException, Exception {
boolean returnValue = false;
try {
// 建立连接
connectToServer();
// 设置传输二进制文件
setFileType(FTP.BINARY_FILE_TYPE);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new IOException("无法连接到FTP服务器:" + ip);
}
/*ftpClient.enterLocalPassiveMode();*/
//进入文件目录
ftpClient.changeWorkingDirectory(CURRENT_DIR);
// 上传文件到ftp
returnValue = ftpClient.storeFile(fileName, buffIn);
if (needDelete) {
ftpClient.deleteFile(fileName);
}
// 输出操作结果信息
if (returnValue) {
System.out.println("uploadToFtp INFO: 将文件上传到ftp:成功!");
} else {
System.out.println("uploadToFtp INFO: 将文件上传到ftp:失败!");
}
buffIn.close();
// 关闭连接
closeConnect();
} catch (FTPConnectionClosedException e) {
System.out.println("ftp连接被关闭!");
throw e;
} catch (Exception e) {
returnValue = false;
System.out.println("ERR : 将文件上传到ftp:失败! ");
throw e;
} finally {
try {
if (buffIn != null) {
buffIn.close();
}
} catch (Exception e) {
System.out.println("ftp关闭输入流时失败!");
}
if (ftpClient.isConnected()) {
closeConnect();
}
}
return returnValue;
}
//下载
public InputStream downloadFile(String filename)
throws IOException {
InputStream in = null;
try {
// 建立连接
connectToServer();
ftpClient.enterLocalPassiveMode();
// 设置传输二进制文件
setFileType(FTP.BINARY_FILE_TYPE);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new IOException("无法连接到FTP服务器:" + ip);
}
ftpClient.changeWorkingDirectory(CURRENT_DIR);
// ftp文件获取文件
in = ftpClient.retrieveFileStream(filename);
} catch (FTPConnectionClosedException e) {
System.out.println("ftp连接被关闭!");
throw e;
} catch (Exception e) {
System.out.println("ERR : 从ftp下载文件 " + filename + " 失败");
}
System.out.println("download file INFO: 将文件下载到本地:成功!");
return in;
}
private void setFileType(int fileType) {
try {
ftpClient.setFileType(fileType);
} catch (Exception e) {
System.out.println("ftp设置传输文件的类型时失败!");
}
}
public void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Exception e) {
System.out.println("ftp连接关闭失败!");
}
}
private void connectToServer() throws FTPConnectionClosedException, Exception {
if (!ftpClient.isConnected()) {
int reply;
try {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");
ftpClient.enterLocalPassiveMode();
ftpClient.connect(ip, port);
ftpClient.login(userName, passWord);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("connectToServer FTP服务器拒绝连接。");
}
} catch (FTPConnectionClosedException ex) {
System.out.println("没有连接数!连接的用户太多,请稍后再试");
throw ex;
} catch (Exception e) {
System.out.println("登录ftp服务器失败");
throw e;
}
}
}
// 检查路径是否存在; 存在返回true,否则返回false。
// public boolean existDirectory(String path) throws IOException {
// boolean flag = false;
// FTPFile[] ftpFileArr = ftpClient.listFiles(path);
// for (FTPFile ftpFile : ftpFileArr) {
// if (ftpFile.isDirectory()
// && ftpFile.getName().equalsIgnoreCase(path)) {
// flag = true;
// break;
// }
// }
// return flag;
// }
//
// public boolean createDirectory(String pathName) throws IOException {
// boolean isSuccess = false;
// try {
// isSuccess = ftpClient.makeDirectory(pathName);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return isSuccess;
// }
//
// public static String getExtention(String fileName) {
// int pos = fileName.lastIndexOf(".");
// return fileName.substring(pos);
// }
//
// public static String getNoPointExtention(String fileName) {
// int pos = fileName.lastIndexOf(".");
// return fileName.substring(pos + 1);
// }
//
// public static String getDateDir(Date dateParam) {
// Calendar cal = Calendar.getInstance();
// if (null != dateParam) {
// cal.setTime(dateParam);
// }
// int currentYear = cal.get(Calendar.YEAR);
// int currentMouth = cal.get(Calendar.MONTH) + 1;
// int currentDay = cal.get(Calendar.DAY_OF_MONTH);
// //int currentHour = cal.get(Calendar.HOUR_OF_DAY);
// //return currentYear+FtpOperation.DIRSPLIT+currentMouth+FtpOperation.DIRSPLIT+currentDay+FtpOperation.DIRSPLIT+currentHour;
// return currentYear + FTPUtils.DIRSPLIT + currentMouth + FTPUtils.DIRSPLIT + currentDay;
// }
}
package com.example.demo01.controller;
import cn.hutool.core.io.FileUtil;
import com.example.demo01.utils.FTPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.File;
import java.io.InputStream;
@Controller
public class FTPController {
@Autowired
private FTPUtils ftpUtils;
@RequestMapping("/uploadToFtp")
public String uploadToFtp() {
File file = new File("D:\\skills1.txt");
InputStream inputStream = FileUtil.getInputStream(file);
try {
ftpUtils.uploadToFtp(inputStream, "skills3.txt", false);
} catch (Exception e) {
e.printStackTrace();
}
return "SUCCESS";
}
@RequestMapping("/downloadFile")
public String downloadFile() {
try {
InputStream inputStream = ftpUtils.downloadFile("skills.txt");
FileUtil.writeFromStream(inputStream, "E:\\skills.txt");
} catch (Exception e) {
e.printStackTrace();
}
return "SUCCESS";
}
}