1. 引入依赖
在pom.xml中添加commons-net依赖:
<dependencies><!-- Apache Commons Net for FTP --><dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.9.0</version></dependency>
</dependencies>
2. 创建FTP上传工具类
创建一个工具类FtpUtil来处理FTP连接和文件上传。
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;public class FtpUtil {private String server;private int port;private String user;private String pass;public FtpUtil(String server, int port, String user, String pass) {this.server = server;this.port = port;this.user = user;this.pass = pass;}/*** 上传文件到ftp服务器* * @param remotePath ftp远程服务的文件路径* @param localFilePath 本地文件路径* @return*/public boolean uploadFile(String remotePath, String localFilePath) {FTPClient ftpClient = new FTPClient();try (InputStream inputStream = new FileInputStream(localFilePath)) {ftpClient.connect(server, port);ftpClient.login(user, pass);ftpClient.enterLocalPassiveMode();ftpClient.setFileType(FTP.BINARY_FILE_TYPE);boolean done = ftpClient.storeFile(remotePath, inputStream);ftpClient.logout();return done;} catch (IOException ex) {ex.printStackTrace();return false;} finally {try {if (ftpClient.isConnected()) {ftpClient.disconnect();}} catch (IOException ex) {ex.printStackTrace();}}}/** * 尝试连接 FTP 服务器并检查连接状态* * @param host* @param port* @return*/public boolean checkFtpServerStatus(String host, int port) {try {FTPClient ftpClient = new FTPClient();ftpClient.connect(host, port);int replyCode = ftpClient.getReplyCode();if (FTPReply.isPositiveCompletion(replyCode)) {// 连接成功return true;}} catch (IOException e) {System.err.println("无法连接到 FTP 服务器: " + e.getMessage());}return false;}}
3. 创建main方法
创建一个main方法来接受文件并上传到FTP服务器。但在此之前我们需要先判断ftp服务器是否联通
public static void main(String[] args) {String server = "192.168.1.xxx";int port = 21;String user = "admin";String pass = "admin@123";FtpUtil ftpUtil = new FtpUtil(server, port, user, pass);boolean b = ftpUtil.checkFtpServerStatus(server, port);System.out.println(b);}
运行结果返回true则表示服务畅通:
创建main方法,发送文件到服务器:
public static void main(String[] args) {String server = "192.168.1.xxx";int port = 21;String user = "admin";String pass = "admin@123";String name = "log.txt";String remotePath = "/data/ftptest" + name;String localPath = "C:\\Users\\Desktop\\" + name;FtpUtil ftpUtil = new FtpUtil(server, port, user, pass);boolean result = ftpUtil.uploadFile(remotePath, localPath);System.out.println(result ? "Upload successful" : "Upload failed");}
以上就是较为简单的一个springboot使用ftp上传文件到远端服务器的代码;