SpringBoot集成FTP

news/2024/9/25 11:16:13/

1.加入核心依赖

        <dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.8.0</version></dependency>

完整依赖

<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><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><!-- hutool --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.22</version></dependency></dependencies>

2.配置文件

ftp:host: 127.0.0.1port: 21username: rootpassword: root

3.FTP配置类

java">package com.example.config;import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author lenovo*/
@Configuration
public class FTPConfig {@Value("${ftp.host}")private String host;@Value("${ftp.port}")private int port;@Value("${ftp.username}")private String username;@Value("${ftp.password}")private String password;@Beanpublic FTPClient ftpClient() {FTPClient ftpClient = new FTPClient();try {ftpClient.connect(host, port);ftpClient.login(username, password);ftpClient.enterLocalPassiveMode();} catch (Exception e) {e.printStackTrace();}return ftpClient;}
}

4.Service层

java">package com.example.service;import cn.hutool.crypto.digest.MD5;
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.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;@Service
public interface FTPService {public boolean uploadFile(MultipartFile file) ;public boolean downloadFile(String remoteFilePath, String localFilePath);public boolean deleteFile(String remoteFilePath);}

实现类:

java">package com.example.service.impl;import com.example.service.FTPService;
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.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;@Service
public class FTPServiceImpl implements FTPService {@Autowiredprivate FTPClient ftpClient;@Overridepublic boolean uploadFile(MultipartFile file) {try {String remoteFilePath = "/w/n";ftpClient.enterLocalPassiveMode(); // 设置Passive ModeftpClient.setBufferSize(1024 * 1024); // 设置缓冲区大小为1MBftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置传输模式为二进制createRemoteDirectory(ftpClient, remoteFilePath);// 切换工作目录boolean success = ftpClient.changeWorkingDirectory(remoteFilePath);if (!success) {System.out.println("切换工作目录失败:" + remoteFilePath);return false;}if (file.isEmpty()) {System.out.println("上传的文件为空");return false;}String s = md5(Objects.requireNonNull(file.getOriginalFilename()));success = ftpClient.storeFile(s, file.getInputStream());if (success) {System.out.println("文件上传成功");} else {System.out.println("文件上传失败");}return success;} catch (IOException e) {e.printStackTrace();System.out.println("文件上传失败:" + e.getMessage());return false;}}@Overridepublic boolean downloadFile(String remoteFilePath, String localFilePath) {try {boolean b = ftpClient.retrieveFile(remoteFilePath, Files.newOutputStream(Paths.get(localFilePath)));System.out.println(b);return b;} catch (IOException e) {e.printStackTrace();return false;}}@Overridepublic boolean deleteFile(String remoteFilePath) {try {return ftpClient.deleteFile(remoteFilePath);} catch (IOException e) {e.printStackTrace();return false;}}// 创建文件夹(多层也可创建) public void createRemoteDirectory(FTPClient ftpClient, String remotePath) throws IOException {String[] dirs = remotePath.split("/");String tempDir = "";for (String dir : dirs) {if (dir.isEmpty()) {continue;}tempDir += "/" + dir;if (!ftpClient.changeWorkingDirectory(tempDir)) {if (!ftpClient.makeDirectory(tempDir)) {throw new IOException("Failed to create remote directory: " + tempDir);}ftpClient.changeWorkingDirectory(tempDir);}}}private static String md5(String fileN) {try {MessageDigest md = MessageDigest.getInstance("MD5");byte[] digest = md.digest(fileN.getBytes());// 将字节数组转换为十六进制字符串StringBuilder str = new StringBuilder();for (byte b : digest) {str.append(String.format("%02x", b));}fileN = str.toString();} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}return fileN;}
}

5.Controller层

java">package com.example.controller;import com.example.service.FTPService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;@RestController
@RequestMapping("/ftp")
public class FTPController {@Autowiredprivate FTPService ftpService;@PostMapping("/upload")public String uploadFile(MultipartFile file) {if (ftpService.uploadFile(file)) {return "File uploaded successfully!";} else {return "Failed to upload file!";}}@GetMapping("/download")public String downloadFile(String remoteFilePath, String localFilePath) {if (ftpService.downloadFile(remoteFilePath, localFilePath)) {return "File downloaded successfully!";} else {return "Failed to download file!";}}@DeleteMapping("/delete")public String deleteFile(@RequestParam String remoteFilePath) {if (ftpService.deleteFile(remoteFilePath)) {return "File deleted successfully!";} else {return "Failed to delete file!";}}
}

6.运行效果

以上就创建好了一个小demo,快去试试吧。


http://www.ppmy.cn/news/1427352.html

相关文章

探索Java设计模式:桥接模式

探索Java设计模式&#xff1a;深入理解与实践桥接模式 桥接模式&#xff08;Bridge Pattern&#xff09;是一种结构型设计模式&#xff0c;它将抽象部分与其实现部分分离&#xff0c;使它们可以独立变化。在Java编程中&#xff0c;桥接模式常用于实现多维度变化、降低类的层次…

【中级软件设计师】上午题08-UML(下):序列图、通信图、状态图、活动图、构件图、部署图

上午题08-UML 1 序列图2 通信图3 状态图3.1 状态和活动3.2 转换和事件 4 活动图5 构件图&#xff08;组件图&#xff09;6 部署图 【中级软件设计师】上午题08-UML(上)&#xff1a;类图、对象图、用例图 UML图总和 静态建模&#xff1a;类图、对象图、用例图 动态建模&#xff…

Table表格(关于个人介绍与图片)

展开行&#xff1a; <el-table :data"gainData" :border"gainParentBorder" style"width: 100%"><el-table-column type"expand"><template #default"props"><div m"4"><h3>工作经…

【Golang】Gin教学-获取请求信息并返回

安装Gin初始化Gin处理所有HTTP请求获取请求的URL和Method获取请求参数根据Content-Type判断请求数据类型处理JSON数据处理表单数据处理文件返回JSON响应启动服务完整代码测试 Gin是一个用Go&#xff08;又称Golang&#xff09;编写的HTTP Web框架&#xff0c;它具有高性能和简洁…

stm32知识记录

文章目录 单片机发送AT指令给ESP8266接收手机app数据的结构体C语言的枚举类枚举类的应用 设置水泵开启关闭代码分析DS18B20的端口 单片机发送AT指令给ESP8266 以下是一个简单的示例&#xff0c;演示了如何使用AT指令从单片机发送数据给ESP8266模块&#xff0c;并通过Wi-Fi发送…

安装SSL证书之后还会有不安全提示怎么办?

安装SSL证书过程中如果遇到错误&#xff0c;不要慌&#xff0c;按照以下步骤进行排查和解决&#xff1a; 1. 仔细阅读错误信息&#xff1a; - 错误消息通常会明确指出问题所在&#xff0c;如证书过期、证书链不完整、域名不匹配等。记下或截图保存具体的错误代码和描述&#xf…

webots学习记录8:R2023b如何在某个零件上添加一个恒定的力(矩)

在webots安装路径下&#xff0c;从include\controller\c\webots\supervisor.h中可以看到如下定义&#xff1a; void wb_supervisor_node_add_force(WbNodeRef node, const double force[3], bool relative); void wb_supervisor_node_add_force_with_offset(WbNodeRef node, c…

2024第八届图像、信号处理和通信国际会议 (ICISPC 2024)即将召开!

2024第八届图像、信号处理和通信国际会议 &#xff08;ICISPC 2024&#xff09;将于2024年7月19-21日在日本福冈举行。启迪思维&#xff0c;引领未来&#xff0c;ICISPC 2024的召开&#xff0c;旨在全球专家学者共襄盛举&#xff0c;聚焦图像信号&#xff0c;在图像中寻找美&am…