spring boot 集成Apache FTPServer 打jar包发布(监听上传动作)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z469441432/article/details/84872975

1.依赖:

        <dependency>
            <groupId>org.apache.mina</groupId>
            <artifactId>mina-core</artifactId>
            <version>2.0.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.mina</groupId>
            <artifactId>mina-integration-beans</artifactId>
            <version>2.0.13</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.mina</groupId>
                    <artifactId>mina-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.ftpserver</groupId>
            <artifactId>ftpserver-core</artifactId>
            <version>1.0.6</version>
        </dependency>

2.user.properties,位于resources/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用户密码和其他设置
ftpserver.user.admin.userpassword=admin
#ftpserver.user.anonymous.homedirectory=C:\\pic
ftpserver.user.admin.homedirectory=/home/pic/
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
#匿名用户密码和其他设置(本处不设置匿名用户密码)
ftpserver.user.anonymous.userpassword=
ftpserver.user.anonymous.homedirectory=/home/pic/
ftpserver.user.anonymous.enableflag=true
ftpserver.user.anonymous.writepermission=true
ftpserver.user.anonymous.maxloginnumber=20
ftpserver.user.anonymous.maxloginperip=2
ftpserver.user.anonymous.idletime=300
ftpserver.user.anonymous.uploadrate=4800
ftpserver.user.anonymous.downloadrate=4800

3.业务处理服务

import com.nongqitong.web.ApplicationContextHelper;
import com.nongqitong.web.pojo.NqtPic;
import com.nongqitong.web.service.NqtPicService;
import org.apache.ftpserver.ftplet.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Date;

@Configuration
public class FtpService extends DefaultFtplet {
   

    @Override
    public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
        //获取上传文件信息
        String path = session.getFileSystemView().getWorkingDirectory().getAbsolutePath();//获取当前路径
        String[] picInfoArr = session.getFileSystemView().getWorkingDirectory().getAbsolutePath();
        String filename = request.getArgument();//获取文件名
        InetSocketAddress serverAddress = session.getServerAddress();
        
        return super.onUploadEnd(session, request);
    }

    @Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
//获取上传文件信息
//        String path = session.getFileSystemView().getWorkingDirectory().getAbsolutePath();//获取当前路径
//        String rootPath = session.getUser().getHomeDirectory();//获取根目录绝对路径
//        String filename = request.getArgument();//获取文件名
        return super.onUploadStart(session, request);
    }
}

4.Server的配置和创建:

FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory listenerFactory = new ListenerFactory();
        listenerFactory.setPort(3131);
        //设置被动模式数据上传的接口范围,云服务器需要开放对应区间的端口给客户端
        DataConnectionConfigurationFactory dataConnectionConfFactory = new DataConnectionConfigurationFactory();
        dataConnectionConfFactory.setPassivePorts("10000-10100");
        listenerFactory.setDataConnectionConfiguration(dataConnectionConfFactory.createDataConnectionConfiguration());
        Listener listener = listenerFactory.createListener();

        serverFactory.addListener("default", listener);
        //第二步中的FtpService,由于FtpService是作为配置(@Configration)启动,因此可以直接通过@Autowire获取实例。
        ftpLets.put("ftpService", service);
        serverFactory.setFtplets(ftpLets);
        //配置文件:位于resources/properties目录下,FTPServer无法直接直接读取Jar包中的配置文                件。将文件复制到指定目录(本文指定到根目录)下然后FTPServer才能读取。
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        String tempPath = System.getProperty("java.io.tmpdir") + System.currentTimeMillis() + ".properties";
        File tempConfig = new File(tempPath);
        

        ClassPathResource resource = new ClassPathResource("properties/users.properties");
        IOUtils.copy(resource.getInputStream(), new FileOutputStream(tempConfig));
        userManagerFactory.setFile(tempConfig);
        userManagerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        server = serverFactory.createServer();

5.监听

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class FtpServerListener implements ServletContextListener {
    //tomcat容器关闭时调用方法stop ftpServer
    public void contextDestroyed(ServletContextEvent sce) {
        WebApplicationContext ctx= WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        MyFtpServer server=(MyFtpServer)ctx.getServletContext().getAttribute(Constants.SERVER_NAME);
        server.stop();
        sce.getServletContext().removeAttribute(Constants.SERVER_NAME);
    }

    //spring 容器初始化调用方法startFtpServer
    public void contextInitialized(ServletContextEvent sce) {
        WebApplicationContext ctx= WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        //spring boot 启动类中创建bean,命名为MyFtp()
        MyFtpServer server=(MyFtpServer) ctx.getBean("MyFtp");
        sce.getServletContext().setAttribute(Constants.SERVER_NAME,server);
        try {
            server.initFtp();
            server.start();

        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("FTP启动失败", e);
        }
    }

}

6.Constants.java

public class Constants {
    public static final String SERVER_NAME="FTP-SERVER";
}

7.启动入口

@SpringBootApplication
@MapperScan("com.nongqitong.web.mapper")
public class WebApplication implements ServletContextInitializer {
    
    public static void main(String[] args) {

		SpringApplication.run(WebApplication.class, args);
	}
    
   	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		servletContext.addListener(FtpServerListener.class);
	}

	@Bean
	public MyFtpServer MyFtp(){
		return  new MyFtpServer();
	}


}

如果要可以下载,则需要设置静态目录映射

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class FtpConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //linux设置
        registry.addResourceHandler("/pic/**").addResourceLocations("file:/home/pic/");
        //windows设置
//        registry.addResourceHandler("/pic/**").addResourceLocations("file:C:/pic/");
    }

}

猜你喜欢

转载自blog.csdn.net/z469441432/article/details/84872975
今日推荐