1. 程式人生 > >spring boot 整合Apache FTPServer 打jar包釋出(監聽上傳動作)

spring boot 整合Apache FTPServer 打jar包釋出(監聽上傳動作)

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/");
    }

}