SpringBoot如何内嵌ftp服务呢?

欣喜 SpringBoot 发布时间:2024-02-04 15:15:49 阅读数:9224 1
下文笔者讲述SpringBoot中内嵌ftp服务的方法及示例分享,如下所示
1.引入相应的依赖
2.编写配置类
          加入相应的配置信息

引入依赖

<!-- https://mvnrepository.com/artifact/org.apache.ftpserver/ftpserver-core -->
        <dependency>
            <groupId>org.apache.ftpserver</groupId>
            <artifactId>ftpserver-core</artifactId>
            <version>1.1.1</version>
        </dependency>

Uploadlistener.java

import org.apache.ftpserver.ftplet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class UploadListener extends DefaultFtplet {
    public static final Logger log= LoggerFactory.getLogger(UploadListener.class);
    /**
     *
     *  开始上传
     * 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 {
        //获取上传文件的上传路径
        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);
        return super.onUploadEnd(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 {
        //获取上传文件的上传路径
        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);
        return super.onUploadStart(session, request);
    }

    @Override
    public FtpletResult onDownloadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
        //todo servies...
        return super.onDownloadStart(session, request);
    }
    @Override
    public FtpletResult onDownloadEnd(FtpSession session, FtpRequest request) throws FtpException, IOException {
        //todo servies...
        return super.onDownloadEnd(session, request);
    }
}

FtpConfig.java

import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置类
 */
@Configuration
public class FtpConfig extends CachingConfigurerSupport {


    @Value("${ftp.port}")
    private Integer ftpPort;


    @Value("${ftp.passivePorts}")
    private String ftpPassivePorts;

    @Value("${ftp.passiveExternalAddress}")
    private String ftpPassiveExternalAddress;




    @Bean
    public FtpServer createFtpServer(){
        FtpServerFactory serverFactory = new FtpServerFactory();

        ListenerFactory factory = new ListenerFactory();/**
         * 被动模式
         */
        DataConnectionConfigurationFactory dataConnectionConfigurationFactory=new DataConnectionConfigurationFactory();
        dataConnectionConfigurationFactory.setIdleTime(60);
        dataConnectionConfigurationFactory.setActiveLocalPort(ftpPort);
        dataConnectionConfigurationFactory.setPassiveIpCheck(true);
        dataConnectionConfigurationFactory.setPassivePorts(ftpPassivePorts);
        dataConnectionConfigurationFactory.setPassiveExternalAddress(ftpPassiveExternalAddress);
        factory.setDataConnectionConfiguration(dataConnectionConfigurationFactory.createDataConnectionConfiguration());
        // replace the default listener
        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不存在");
        }

        userManagerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
        serverFactory.setUserManager(userManagerFactory.createUserManager());

        Map<String, Ftplet> m = new HashMap<String, Ftplet>();
        m.put("miaFtplet", new UploadListener());

        serverFactory.setFtplets(m);
        // start the server
        FtpServer server = serverFactory.createServer();



        return server;
    }
}

InitFtpServer.java

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.ftplet.FtpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.commandlinerunner;
import org.springframework.stereotype.Component;

/**
 * springboot启动时初始化ftpserver
 */
@Component
public class InitFtpServer implements CommandLineRunner {

    public static final Logger log = LoggerFactory.getLogger(FtpServer.class);


    @Autowired
    private FtpServer server;


    @Override
    public void run(String... args) throws Exception {
        try {
            server.start();
            log.info(">>>>>>>ftp start success ");
        } catch (FtpException e) {
            e.printStackTrace();
            log.error(">>>>>>>ftp start error {}", e);

        }
    }
}

resource下创建users.properties

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

#表示admin的密码是123456 以下都是admin的参数设置,可以多个
ftpserver.user.admin.userpassword=123456
ftpserver.user.admin.homedirectory=/home/data/ftp
ftpserver.user.admin.enableflag=true
ftpserver.user.admin.writepermission=true
ftpserver.user.admin.maxloginnumber=0
ftpserver.user.admin.maxloginperip=0
ftpserver.user.admin.idletime=0
ftpserver.user.admin.uploadrate=0
ftpserver.user.admin.downloadrate=0


yml配置文件加入

ftp:
  port: 21 #ftp连接端口
  passivePorts: 20  #被动连接数据传输端口
  passiveExternalAddress: 127.0.0.1 #部署的服务器ip地址
启动Spring Boot,则一个简易的FTP服务及创建成功
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202402/7909.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者