本地微服务springboot集成ftp服务器

embedded/2024/9/23 17:25:28/

可分为四步,话不多说

1、引入apache ftp依赖

        <dependency><groupId>org.apache.ftpserver</groupId><artifactId>ftpserver-core</artifactId><version>1.1.1</version></dependency>

2、创建ftp所需用户信息 users.properties

例如配置一个root用户:
#密码 配置新的用户
ftpserver.user.root.userpassword=root123
#主目录,这里可以自定义自己的主目录
ftpserver.user.root.homedirectory=D:\\home\\ftp
#当前用户可用
ftpserver.user.root.enableflag=true
#具有上传权限
ftpserver.user.root.writepermission=true
#最大登陆用户数为20
ftpserver.user.root.maxloginnumber=20
#同IP登陆用户数为2
ftpserver.user.root.maxloginperip=2
#空闲时间为300秒
ftpserver.user.root.idletime=300
#上传速率限制为480000字节每秒
ftpserver.user.root.uploadrate=48000000
#下载速率限制为480000字节每秒
ftpserver.user.root.downloadrate=48000000 

3、创建ftp配置信息

@Slf4j
@Configuration
public class FtpConfig extends CachingConfigurerSupport {@Value("${ftp.port}")private Integer ftpPort;@Value("${ftp.activePort}")private Integer ftpActivePort;@Value("${ftp.passivePorts}")private String ftpPassivePorts;@Beanpublic FtpServer createFtpServer(){FtpServerFactory serverFactory = new FtpServerFactory();ListenerFactory factory = new ListenerFactory();// ftp端口factory.setPort(ftpPort);DataConnectionConfigurationFactory dataConnectionConfigurationFactory=new DataConnectionConfigurationFactory();//设置多少时间后关闭一个闲置的链接,单位是秒,0代表不设置dataConnectionConfigurationFactory.setIdleTime(60*60*24);//设置主动模式端口dataConnectionConfigurationFactory.setActiveLocalPort(ftpActivePort);dataConnectionConfigurationFactory.setPassiveIpCheck(true);//设置被动模式端口dataConnectionConfigurationFactory.setPassivePorts(ftpPassivePorts);factory.setDataConnectionConfiguration(dataConnectionConfigurationFactory.createDataConnectionConfiguration());//替换默认监听器serverFactory.addListener("default", factory.createListener());PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();try {ClassPathResource classPathResource = new ClassPathResource("users.properties");userManagerFactory.setUrl(classPathResource.getURL());} catch (Exception e){
//            throw new RuntimeException("配置文件users.properties不存在");log.error("users.properties is not exist.");}userManagerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());serverFactory.setUserManager(userManagerFactory.createUserManager());//自定义用户事件Map<String, Ftplet> ftpLets = new HashMap<String, Ftplet>();ftpLets.put("ftpService", new CustomFtplet());serverFactory.setFtplets(ftpLets);//创建ftp服务器FtpServer server = serverFactory.createServer();try {server.start();} catch (FtpException e) {log.error("ftp server init failed.");}log.info("ftp server init successfully.");return server;}
}

4、自定义一些用户事件

@Slf4j
public class CustomFtplet extends DefaultFtplet {@Overridepublic FtpletResult onLogin(FtpSession session, FtpRequest request) throws FtpException, IOException {try {User user = session.getUser();String requestLine = request.getRequestLine();String name = user.getName();log.info("用户:'{}'登录成功,requestLine:'{}'", name, requestLine);}catch (Exception exception){log.error("用户:'{}'登录异常:{}", session.toString(),exception.toString());}return super.onLogin(session, request);}@Overridepublic FtpletResult onConnect(FtpSession session) throws FtpException, IOException {try {UUID sessionId = session.getSessionId();InetSocketAddress clientAddress = session.getClientAddress();String hostString = clientAddress.getHostString();log.info("用户:'{}',hostString:'{}',建立连接", sessionId, hostString);}catch (Exception exception){log.error("用户:'{}',建立连接异常:{}", session.toString(),exception.toString());}return super.onConnect(session);}@Overridepublic FtpletResult onDisconnect(FtpSession session) throws FtpException, IOException {try{String name = session.getUser().getName();String hostString = session.getClientAddress().getHostString();log.info("用户:'{}',hostString:'{}',断开连接", name, hostString);}catch (Exception exception){log.error("用户:'{}',断开连接异常:{}", session.toString(),exception.toString());}return super.onDisconnect(session);}/****  开始上传* Override this method to intercept uploads* @param session The current {@link FtpSession}* @param request The current {@link FtpRequest}* @return The action for the container to take* @throws FtpException* @throws IOException*/@Overridepublic FtpletResult onUploadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {try {//获取上传文件的上传路径String path = session.getUser().getHomeDirectory();//自动创建上传路径File file=new File(path);if (!file.exists()){file.mkdirs();}//获取上传用户String name = session.getUser().getName();//获取上传文件名String filename = request.getArgument();log.info("用户:'{}',上传文件到目录:'{}',文件名称为:'{}',状态:开始上传~", name, path, filename);}catch (Exception exception){log.error("用户:'{}',上传文件异常:{}", session.toString(),exception.toString());}return super.onUploadStart(session, request);}/***  上传完成* Override this method to handle uploads after completion* @param session The current {@link FtpSession}* @param request The current {@link FtpRequest}* @return The action for the container to take* @throws FtpException* @throws IOException*/@Overridepublic FtpletResult onUploadEnd(FtpSession session, FtpRequest request) throws FtpException, IOException {try {//获取上传文件的上传路径String path = session.getUser().getHomeDirectory();//获取上传用户String name = session.getUser().getName();//获取上传文件名String filename = request.getArgument();File file=new File(path+"/"+filename);if (file.exists()){System.out.println(file);}log.info("用户:'{}',上传文件到目录:'{}',文件名称为:'{},状态:成功!'", name, path, filename);}catch (Exception exception){log.error("用户:'{}',上传文件结束异常:{}", session.toString(),exception.toString());}return super.onUploadEnd(session, request);}
}

结果展示:可以使用fileliza进行登录

10:04:57.432 [NioProcessor-3] INFO  o.a.f.l.n.FtpLoggingFilter - [log,186] - CREATED
10:04:57.435 [pool-5-thread-1] INFO  o.a.f.l.n.FtpLoggingFilter - [log,186] - OPENED
10:05:05.203 [pool-5-thread-1] INFO  c.c.s.c.CustomFtplet - [onConnect,33] - 用户:'3bfb89a0-32b4-43f2-8ca6-0a01c88bcc8b',hostString:'10.192.31.179',建立连接
10:05:05.256 [pool-5-thread-1] INFO  o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 220 Service ready for new user.10:05:05.258 [pool-5-thread-1] INFO  o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: AUTH TLS
10:05:05.259 [pool-5-thread-1] INFO  o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 431 Service is unavailable.10:05:05.259 [pool-5-thread-1] INFO  o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: AUTH SSL
10:05:05.260 [pool-5-thread-2] INFO  o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 431 Service is unavailable.10:05:19.359 [pool-5-thread-1] INFO  o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: USER root
10:05:19.362 [pool-5-thread-2] INFO  o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 331 User name okay, need password for root.10:05:19.362 [pool-5-thread-2] INFO  o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: PASS *****
10:05:19.376 [pool-5-thread-2] INFO  o.a.f.c.impl.PASS - [execute,245] - Login success - root
10:05:26.483 [pool-5-thread-2] INFO  c.c.s.c.CustomFtplet - [onLogin,20] - 用户:'root'登录成功,requestLine:'PASS root123'
10:05:26.484 [pool-5-thread-2] INFO  o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 230 User logged in, proceed.


http://www.ppmy.cn/embedded/22132.html

相关文章

『大模型笔记』Code Example: Function Calling with ChatGPT

Code Example: Function Calling with ChatGPT 文章目录 一. Code Example: Function Calling with ChatGPT二. 参考文献一. Code Example: Function Calling with ChatGPT from openai import OpenAI from dotenv import load_dotenv import json# -------------------------…

Git快速入门技巧常见问题

文章目录 Git快速入门技巧&常见问题Git安装使用&配置1.Git安装2.Git使用自建本地仓库克隆仓库创建远程代码仓库分支branch 3.Git工作流程 Git快速入门技巧&常见问题 前情提要 ​ 最近在来回不停切环境开发项目&#xff0c;总是发现各种奇奇怪怪的问题&#xff0c;解…

【网络原理】TCP协议的连接管理机制(三次握手和四次挥手)

系列文章目录 【网络通信基础】网络中的常见基本概念 【网络编程】网络编程中的基本概念及Java实现UDP、TCP客户端服务器程序&#xff08;万字博文&#xff09; 【网络原理】UDP协议的报文结构 及 校验和字段的错误检测机制&#xff08;CRC算法、MD5算法&#xff09; 【网络…

如何讲好ppt演讲技巧(4篇)

如何讲好ppt演讲技巧&#xff08;4篇&#xff09; 如何讲好PPT演讲技巧&#xff08;四篇&#xff09; **篇&#xff1a;精心准备&#xff0c;奠定演讲基础 一个成功的PPT演讲&#xff0c;离不开精心的准备。首先&#xff0c;要确定演讲的主题和目标&#xff0c;确保演讲内容清…

【汇编】#6 80x86指令系统其二(串处理与控制转移与子函数)

文章目录 一、串处理指令1. 与 REP 协作的 MOVS / STOS / LODS的指令1.1 重复前缀指令REP1.2 字符串传送指令&#xff08;Move String Instruction&#xff09;1.2 存串指令&#xff08;Store String Instruction&#xff09;1.3 取字符串指令&#xff08;Load String Instruct…

visionPro链接相机

搜索Cognex GigE Vision Configura… 修改子网掩码为255.255.255.0 配置驱动程序 更新驱动&#xff08;如果能够选择9014Bytes&#xff0c;跳过此步骤&#xff09; 更新更改 相机ip配置 打开visionPro 选择照相机 查看实时画面 运行保存图像

Oracle对空值(NULL)的 聚合函数 排序

除count之外sum、avg、max、min都为null&#xff0c;count为0 Null 不支持加减乘除&#xff0c;大小比较&#xff0c;相等比较&#xff0c;否则只能为空&#xff1b;只能用‘is [not] null’来进行判断&#xff1b; Max等聚合函数会自动“过滤null” null排序默认最大&#xf…

Pycharm:常用插件安装和使用

简介&#xff1a;好用的插件可以美化界面或者提升效率&#xff0c;使工作事半功倍。 推荐插件&#xff1a; 1、CSV插件&#xff1a;美化csv数据展示 2、Translation&#xff1a;翻译的插件&#xff0c;可以进行中英互译 3、CodeGlance&#xff1a;代码小地图 4、Markdown …