springboot整合ftp服务器实现上传与下载
1. 添加依赖
在项目的pom.xml文件中添加spring-boot-starter-web和commons-net的依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
</dependencies>
2. 配置FTP连接信息
在application.properties或application.yml文件中配置FTP服务器的地址、端口、用户名和密码:
ftp.host=ftp.example.com
ftp.port=21
ftp.username=your_username
ftp.password=your_password
3. 创建FTP工具类
创建一个名为FtpUtil的工具类,用于封装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;
import java.util.ArrayList;
import java.util.List;
public class FtpUtil {
private static FTPClient ftpClient = new FTPClient();
public static void connect(String host, int port, String username, String password) throws IOException {
ftpClient.connect(host, port);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
ftpClient.disconnect();
throw new IOException("FTP server refused connection");
}
boolean success = ftpClient.login(username, password);
if (!success) {
ftpClient.logout();
throw new IOException("FTP login failed");
}
}
public static void disconnect() {
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static List<String> listFiles(String directory) throws IOException {
List<String> fileNames = new ArrayList<>();
ftpClient.changeWorkingDirectory(directory);
String[] names = ftpClient.listNames();
for (String name : names) {
fileNames.add(name);
}
return fileNames;
}
public static void uploadFile(String localFilePath, String remoteFilePath) throws IOException {
InputStream inputStream = new FileInputStream(localFilePath);
boolean done = ftpClient.storeFile(remoteFilePath, inputStream);
inputStream.close();
if (!done) {
throw new IOException("File upload failed");
}
}
public static void downloadFile(String remoteFilePath, String localFilePath) throws IOException {
InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
FileOutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
}
4. 使用FTP工具类进行文件上传和下载操作
在需要使用FTP的地方,调用FtpUtil类的方法进行文件上传和下载操作。例如:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@Service
public class FtpService {
@Autowired
private FtpUtil ftpUtil;
public void uploadFile(MultipartFile file, String remoteDirectory) throws IOException {
String localFilePath = file.getOriginalFilename();
String remoteFilePath = remoteDirectory + "/" + file.getOriginalFilename();
ftpUtil.uploadFile(localFilePath, remoteFilePath);
}
public void downloadFile(String remoteFilePath, String localDirectory) throws IOException {
String localFilePath = localDirectory + "/" + Paths.get(remoteFilePath).getFileName().toString();
ftpUtil.downloadFile(remoteFilePath, localFilePath);
}
}
5. 在Controller中使用FtpService进行文件上传和下载操作
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@RestController
@RequestMapping("/ftp")
public class FtpController {
@Autowired
private FtpService ftpService;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("directory") String directory) throws IOException {
ftpService.uploadFile(file, directory);
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}
@GetMapping("/download/{filename}")
public ResponseEntity<byte[]> downloadFile(@PathVariable("filename") String filename) throws IOException {
byte[] fileData = ftpService.downloadFile(filename);
return new ResponseEntity<>(fileData, HttpStatus.OK);
}
}