当前位置:   article > 正文

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

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

可分为四步,话不多说

1、引入apache ftp依赖

  1. <dependency>
  2. <groupId>org.apache.ftpserver</groupId>
  3. <artifactId>ftpserver-core</artifactId>
  4. <version>1.1.1</version>
  5. </dependency>

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

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

3、创建ftp配置信息

  1. @Slf4j
  2. @Configuration
  3. public class FtpConfig extends CachingConfigurerSupport {
  4. @Value("${ftp.port}")
  5. private Integer ftpPort;
  6. @Value("${ftp.activePort}")
  7. private Integer ftpActivePort;
  8. @Value("${ftp.passivePorts}")
  9. private String ftpPassivePorts;
  10. @Bean
  11. public FtpServer createFtpServer(){
  12. FtpServerFactory serverFactory = new FtpServerFactory();
  13. ListenerFactory factory = new ListenerFactory();
  14. // ftp端口
  15. factory.setPort(ftpPort);
  16. DataConnectionConfigurationFactory dataConnectionConfigurationFactory=new DataConnectionConfigurationFactory();
  17. //设置多少时间后关闭一个闲置的链接,单位是秒,0代表不设置
  18. dataConnectionConfigurationFactory.setIdleTime(60*60*24);
  19. //设置主动模式端口
  20. dataConnectionConfigurationFactory.setActiveLocalPort(ftpActivePort);
  21. dataConnectionConfigurationFactory.setPassiveIpCheck(true);
  22. //设置被动模式端口
  23. dataConnectionConfigurationFactory.setPassivePorts(ftpPassivePorts);
  24. factory.setDataConnectionConfiguration(dataConnectionConfigurationFactory.createDataConnectionConfiguration());
  25. //替换默认监听器
  26. serverFactory.addListener("default", factory.createListener());
  27. PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
  28. try {
  29. ClassPathResource classPathResource = new ClassPathResource("users.properties");
  30. userManagerFactory.setUrl(classPathResource.getURL());
  31. } catch (Exception e){
  32. // throw new RuntimeException("配置文件users.properties不存在");
  33. log.error("users.properties is not exist.");
  34. }
  35. userManagerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
  36. serverFactory.setUserManager(userManagerFactory.createUserManager());
  37. //自定义用户事件
  38. Map<String, Ftplet> ftpLets = new HashMap<String, Ftplet>();
  39. ftpLets.put("ftpService", new CustomFtplet());
  40. serverFactory.setFtplets(ftpLets);
  41. //创建ftp服务器
  42. FtpServer server = serverFactory.createServer();
  43. try {
  44. server.start();
  45. } catch (FtpException e) {
  46. log.error("ftp server init failed.");
  47. }
  48. log.info("ftp server init successfully.");
  49. return server;
  50. }
  51. }

4、自定义一些用户事件

  1. @Slf4j
  2. public class CustomFtplet extends DefaultFtplet {
  3. @Override
  4. public FtpletResult onLogin(FtpSession session, FtpRequest request) throws FtpException, IOException {
  5. try {
  6. User user = session.getUser();
  7. String requestLine = request.getRequestLine();
  8. String name = user.getName();
  9. log.info("用户:'{}'登录成功,requestLine:'{}'", name, requestLine);
  10. }catch (Exception exception){
  11. log.error("用户:'{}'登录异常:{}", session.toString(),exception.toString());
  12. }
  13. return super.onLogin(session, request);
  14. }
  15. @Override
  16. public FtpletResult onConnect(FtpSession session) throws FtpException, IOException {
  17. try {
  18. UUID sessionId = session.getSessionId();
  19. InetSocketAddress clientAddress = session.getClientAddress();
  20. String hostString = clientAddress.getHostString();
  21. log.info("用户:'{}',hostString:'{}',建立连接", sessionId, hostString);
  22. }catch (Exception exception){
  23. log.error("用户:'{}',建立连接异常:{}", session.toString(),exception.toString());
  24. }
  25. return super.onConnect(session);
  26. }
  27. @Override
  28. public FtpletResult onDisconnect(FtpSession session) throws FtpException, IOException {
  29. try{
  30. String name = session.getUser().getName();
  31. String hostString = session.getClientAddress().getHostString();
  32. log.info("用户:'{}',hostString:'{}',断开连接", name, hostString);
  33. }catch (Exception exception){
  34. log.error("用户:'{}',断开连接异常:{}", session.toString(),exception.toString());
  35. }
  36. return super.onDisconnect(session);
  37. }
  38. /**
  39. *
  40. * 开始上传
  41. * Override this method to intercept uploads
  42. * @param session The current {@link FtpSession}
  43. * @param request The current {@link FtpRequest}
  44. * @return The action for the container to take
  45. * @throws FtpException
  46. * @throws IOException
  47. */
  48. @Override
  49. public FtpletResult onUploadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
  50. try {
  51. //获取上传文件的上传路径
  52. String path = session.getUser().getHomeDirectory();
  53. //自动创建上传路径
  54. File file=new File(path);
  55. if (!file.exists()){
  56. file.mkdirs();
  57. }
  58. //获取上传用户
  59. String name = session.getUser().getName();
  60. //获取上传文件名
  61. String filename = request.getArgument();
  62. log.info("用户:'{}',上传文件到目录:'{}',文件名称为:'{}',状态:开始上传~", name, path, filename);
  63. }catch (Exception exception){
  64. log.error("用户:'{}',上传文件异常:{}", session.toString(),exception.toString());
  65. }
  66. return super.onUploadStart(session, request);
  67. }
  68. /**
  69. * 上传完成
  70. * Override this method to handle uploads after completion
  71. * @param session The current {@link FtpSession}
  72. * @param request The current {@link FtpRequest}
  73. * @return The action for the container to take
  74. * @throws FtpException
  75. * @throws IOException
  76. */
  77. @Override
  78. public FtpletResult onUploadEnd(FtpSession session, FtpRequest request) throws FtpException, IOException {
  79. try {
  80. //获取上传文件的上传路径
  81. String path = session.getUser().getHomeDirectory();
  82. //获取上传用户
  83. String name = session.getUser().getName();
  84. //获取上传文件名
  85. String filename = request.getArgument();
  86. File file=new File(path+"/"+filename);
  87. if (file.exists()){
  88. System.out.println(file);
  89. }
  90. log.info("用户:'{}',上传文件到目录:'{}',文件名称为:'{},状态:成功!'", name, path, filename);
  91. }catch (Exception exception){
  92. log.error("用户:'{}',上传文件结束异常:{}", session.toString(),exception.toString());
  93. }
  94. return super.onUploadEnd(session, request);
  95. }
  96. }

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

  1. 10:04:57.432 [NioProcessor-3] INFO o.a.f.l.n.FtpLoggingFilter - [log,186] - CREATED
  2. 10:04:57.435 [pool-5-thread-1] INFO o.a.f.l.n.FtpLoggingFilter - [log,186] - OPENED
  3. 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',建立连接
  4. 10:05:05.256 [pool-5-thread-1] INFO o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 220 Service ready for new user.
  5. 10:05:05.258 [pool-5-thread-1] INFO o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: AUTH TLS
  6. 10:05:05.259 [pool-5-thread-1] INFO o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 431 Service is unavailable.
  7. 10:05:05.259 [pool-5-thread-1] INFO o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: AUTH SSL
  8. 10:05:05.260 [pool-5-thread-2] INFO o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 431 Service is unavailable.
  9. 10:05:19.359 [pool-5-thread-1] INFO o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: USER root
  10. 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.
  11. 10:05:19.362 [pool-5-thread-2] INFO o.a.f.l.n.FtpLoggingFilter - [messageReceived,84] - RECEIVED: PASS *****
  12. 10:05:19.376 [pool-5-thread-2] INFO o.a.f.c.impl.PASS - [execute,245] - Login success - root
  13. 10:05:26.483 [pool-5-thread-2] INFO c.c.s.c.CustomFtplet - [onLogin,20] - 用户:'root'登录成功,requestLine:'PASS root123'
  14. 10:05:26.484 [pool-5-thread-2] INFO o.a.f.l.n.FtpLoggingFilter - [log,157] - SENT: 230 User logged in, proceed.

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号