springboot整合ftp服务器实现上传与下载

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);
    }
}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值