springboot中使用FTP上传文件
时间: 2023-10-24 13:26:14 浏览: 111
在Spring Boot应用中使用FTP上传文件可以使用Apache Commons Net库提供的FTP客户端实现。以下是一个简单示例:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
```
2. 创建FTP客户端
使用以下代码创建FTP客户端:
```java
public class FtpClientHelper {
private String server;
private int port;
private String username;
private String password;
private FTPClient ftpClient;
public FtpClientHelper(String server, int port, String username, String password) {
this.server = server;
this.port = port;
this.username = username;
this.password = password;
ftpClient = new FTPClient();
}
public void connect() throws IOException {
ftpClient.connect(server, port);
ftpClient.login(username, password);
}
public void disconnect() throws IOException {
ftpClient.logout();
ftpClient.disconnect();
}
public boolean isConnected() {
return ftpClient.isConnected();
}
public void uploadFile(File file, String remoteDir) throws IOException {
InputStream inputStream = new FileInputStream(file);
ftpClient.storeFile(remoteDir + "/" + file.getName(), inputStream);
inputStream.close();
}
}
```
3. 使用FTP客户端上传文件
在需要上传文件的地方,创建FTP客户端实例并连接到FTP服务器:
```java
FtpClientHelper ftpClientHelper = new FtpClientHelper("ftp.example.com", 21, "username", "password");
ftpClientHelper.connect();
```
然后,使用FTP客户端上传文件:
```java
File file = new File("path/to/local/file");
String remoteDir = "/path/to/remote/dir";
ftpClientHelper.uploadFile(file, remoteDir);
```
最后,记得在上传完成后断开FTP连接:
```java
ftpClientHelper.disconnect();
```
阅读全文