Spring Boot:将文件推送到 FTP 服务器

在企业应用中,将文件推送到 FTP 服务器是一个常见的需求。本文将介绍如何在 Spring Boot 项目中实现将文件推送到 FTP 服务器,包括引入依赖、自定义配置和编写代码示例。

1. 引入依赖

首先,在 Spring Boot 项目的 pom.xml 文件中引入 Apache Commons Net 依赖,它是一个用于处理 FTP 操作的库:

bash 复制代码
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.8.0</version>
</dependency>

2. 自定义 FTP 配置

创建一个配置类 FTPConfig,用于配置 FTP 连接的相关参数:

bash 复制代码
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "ftp")
public class FTPConfig {

    private String server;
    private int port;
    private String user;
    private String password;

    // Getters and Setters
    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

在 application.yml 文件中添加 FTP 服务器的相关配置:

bash 复制代码
ftp:
  server: ftp.example.com
  port: 21
  user: ftpuser
  password: ftppassword

3. 实现 FTP 服务类

创建一个服务类 FTPService,用于连接 FTP 服务器并上传文件:

bash 复制代码
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class FTPService {

    @Autowired
    private FTPConfig ftpConfig;

    public void uploadFile(String remotePath, MultipartFile file) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(ftpConfig.getServer(), ftpConfig.getPort());
            ftpClient.login(ftpConfig.getUser(), ftpConfig.getPassword());
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            try (InputStream inputStream = file.getInputStream()) {
                boolean done = ftpClient.storeFile(remotePath, inputStream);
                if (done) {
                    System.out.println("File " + file.getOriginalFilename() + " has been uploaded successfully.");
                } else {
                    throw new IOException("Failed to upload file " + file.getOriginalFilename());
                }
            }
        } finally {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
    }
}

4. 编写控制器类

创建一个控制器类 FTPController,用于处理文件上传请求并调用 FTPService 进行文件上传:

bash 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class FTPController {

    @Autowired
    private FTPService ftpService;

    @PostMapping("/uploadFile")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String remotePath = "/uploads/" + file.getOriginalFilename();
            ftpService.uploadFile(remotePath, file);
            return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

完整代码结构

bash 复制代码
src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── ftp
│   │               ├── FTPApplication.java
│   │               ├── FTPConfig.java
│   │               ├── FTPService.java
│   │               └── FTPController.java
│   └── resources
│       └── application.yml

测试上传文件到 FTP 服务器

启动 Spring Boot 应用程序,使用 Postman 或类似工具发送 POST 请求至以下 URL,并上传要推送到 FTP 服务器的文件:

bash 复制代码
POST http://localhost:8080/uploadFile

请求参数:

复制代码
file: 上传的文件。

总结

通过本文,我们成功地在 Spring Boot 项目中实现了将文件推送到 FTP 服务器的功能。我们通过引入 Apache Commons Net 依赖、自定义 FTP 配置、创建 FTP 服务类和控制器类,实现了文件的上传和管理。这种方式可以帮助我们在各种应用场景中将文件高效地推送到 FTP 服务器,方便文件的存储和共享。

相关推荐
涡能增压发动积7 分钟前
当你不了解“异步”时请慎用“异步”——记一次生产环境故障排查之旅
后端
文心快码BaiduComate12 分钟前
用Comate Zulu开发一款微信小程序
前端·后端·微信小程序
用户83562907805114 分钟前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_15 分钟前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
ytadpole15 分钟前
Java 25 新特性 更简洁、更高效、更现代
java·后端
风一样的树懒1 小时前
死信队列:你在正确使用么?
后端
RoyLin1 小时前
TypeScript设计模式:门面模式
前端·后端·typescript
JavaGuide1 小时前
JDK 25(长期支持版) 发布,新特性解读!
java·后端
weiwenhao2 小时前
关于 nature 编程语言
人工智能·后端·开源
薛定谔的算法2 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端