赞
踩
可分为四步,话不多说
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;
-
-
- @Bean
- public 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 {
-
- @Override
- public 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);
- }
-
- @Override
- public 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);
- }
-
- @Override
- public 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
- */
- @Override
- public 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
- */
- @Override
- public 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.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。