封装ftp-spring-boot-starter并实现文件上传

Updated on in 编程技术 with 0 views and 0 comments

1 准备

  • FTP 服务器,匿名 or 用户名/密码均可

2 封装 ftp-spring-boot-starter

2.1 配置类 FtpProperties.java

 1package com.coctrl.ftp.configuration;
 2
 3import org.springframework.boot.context.properties.ConfigurationProperties;
 4import org.springframework.stereotype.Component;
 5
 6/**
 7 * 类 FtpProperties 功能描述:
 8 *
 9 * @author kangaroo hy
10 * @version 0.0.1
11 * @date 2020/11/10
12 */
13@Component
14@ConfigurationProperties(prefix = "coctrl.ftp")
15public class FtpProperties {
16
17    /**
18     * 服务器地址,默认 localhost
19     */
20    private String host = "localhost";
21
22    /**
23     * 通信端口,默认 21
24     */
25    private Integer port = 21;
26
27    /**
28     * 用户名
29     */
30    private String username = "";
31
32    /**
33     * 密码
34     */
35    private String password = "";
36
37    /**
38     * 文件上传路径,支持一级,可以不用 /
39     *  如:test,不用:/test
40     */
41    private String path = "";
42
43    public String getHost() {
44        return host;
45    }
46
47    public void setHost(String host) {
48        this.host = host;
49    }
50
51    public Integer getPort() {
52        return port;
53    }
54
55    public void setPort(Integer port) {
56        this.port = port;
57    }
58
59    public String getUsername() {
60        return username;
61    }
62
63    public void setUsername(String username) {
64        this.username = username;
65    }
66
67    public String getPassword() {
68        return password;
69    }
70
71    public void setPassword(String password) {
72        this.password = password;
73    }
74
75    public String getPath() {
76        return path;
77    }
78
79    public void setPath(String path) {
80        this.path = path;
81    }
82}
83

2.2 自动装配类 FtpAutoConfiguration.java

 1package com.coctrl.ftp.configuration;
 2
 3import com.coctrl.ftp.service.FtpService;
 4import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
 5import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 6import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
 7import org.springframework.boot.context.properties.EnableConfigurationProperties;
 8import org.springframework.context.annotation.Bean;
 9import org.springframework.context.annotation.Configuration;
10
11/**
12 * @author kangaroo hy
13 * @date 2020/4/25
14 * @desc ftp-spring-boot-starter
15 * @since 0.0.1
16 */
17@Configuration
18@EnableConfigurationProperties(FtpProperties.class)
19@ConditionalOnClass(FtpService.class)
20@ConditionalOnProperty(prefix = "coctrl.ftp", value = "enabled", matchIfMissing = true)
21public class FtpAutoConfiguration {
22    private final FtpProperties properties;
23
24    public FtpAutoConfiguration(FtpProperties properties) {
25        this.properties = properties;
26    }
27
28    @Bean
29    @ConditionalOnMissingBean(FtpService.class)
30    public FtpService ftpService() {
31        return new FtpService(properties);
32    }
33}
34

2.3 服务类 FtpService.java

 1package com.coctrl.ftp.service;
 2
 3import com.coctrl.ftp.configuration.FtpProperties;
 4import org.apache.commons.net.ftp.FTP;
 5import org.apache.commons.net.ftp.FTPClient;
 6import org.apache.commons.net.ftp.FTPReply;
 7import org.apache.log4j.Logger;
 8import org.springframework.stereotype.Service;
 9import org.springframework.util.StringUtils;
10
11import java.io.IOException;
12import java.io.InputStream;
13import java.util.Queue;
14import java.util.concurrent.ConcurrentLinkedQueue;
15
16/**
17 * 类 FtpService 功能描述:
18 *
19 * @author kangaroo hy
20 * @version 0.0.1
21 * @date 2020/11/10
22 */
23@Service
24public class FtpService {
25    public static final Logger logger = Logger.getLogger(FtpService.class);
26
27    private final FtpProperties properties;
28
29    private Queue<FTPClient> queue = new ConcurrentLinkedQueue<>();
30
31    public FtpService(FtpProperties properties) {
32        this.properties = properties;
33    }
34
35    public boolean uploadFile(String fileName, InputStream inputStream) {
36        FTPClient ftpClient = connect();
37        if (ftpClient != null) {
38            try {
39                boolean b = ftpClient.storeFile(fileName, inputStream);
40                if (b) {
41                    logger.info("上传成功");
42                } else {
43                    logger.info("上传失败");
44                }
45                inputStream.close();
46                return b;
47            } catch (IOException e) {
48                logger.info("上传失败:" + e.getMessage());
49            } finally {
50                disconnect(ftpClient);
51            }
52        }
53        return false;
54    }
55
56    private FTPClient connect() {
57        FTPClient client = queue.poll();
58        if (client != null) {
59            return client;
60        }
61        FTPClient ftpClient = new FTPClient();
62        ftpClient.setControlEncoding("utf-8");
63        try {
64            ftpClient.connect(properties.getHost(), properties.getPort());
65            if (StringUtils.isEmpty(properties.getUsername()) || StringUtils.isEmpty(properties.getPassword())) {
66                ftpClient.login("anonymous", null);
67            } else {
68                ftpClient.login(properties.getUsername(), properties.getPassword());
69            }
70            int replyCode = ftpClient.getReplyCode();
71            if (!FTPReply.isPositiveCompletion(replyCode)) {
72                logger.error("连接服务器失败");
73                throw new IOException("不能连接到FTP服务器:" + properties.getHost());
74            }
75            logger.info("连接服务器成功");
76            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
77            ftpClient.enterLocalPassiveMode();
78            boolean b = ftpClient.makeDirectory(properties.getPath());
79            if (b) {
80                logger.info("路径创建成功");
81            } else {
82                logger.info("路径已存在,直接使用");
83            }
84            ftpClient.changeWorkingDirectory(properties.getPath());
85            queue.add(ftpClient);
86            return ftpClient;
87        } catch (IOException e) {
88            logger.error("连接服务器成功", e);
89            return null;
90        }
91    }
92
93    void disconnect(FTPClient client) {
94        queue.add(client);
95    }
96}
97

2.4 spring.factories

1# Auto Configure
2org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
3  com.coctrl.ftp.configuration.FtpAutoConfiguration
4

2.6 pom.xml

 1<?xml version="1.0" encoding="UTF-8"?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4    <modelVersion>4.0.0</modelVersion>
 5    <groupId>com.coctrl</groupId>
 6    <artifactId>ftp-spring-boot-starter</artifactId>
 7    <version>0.0.1</version>
 8    <name>ftp-spring-boot-starter</name>
 9    <description>ftp-spring-boot-starter</description>
10
11    <properties>
12        <java.version>1.8</java.version>
13        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
14        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
15        <spring-boot.version>2.1.12.RELEASE</spring-boot.version>
16        <commons-net.version>3.6</commons-net.version>
17        <slf4j.version>1.7.25</slf4j.version>
18    </properties>
19
20    <dependencies>
21        <dependency>
22            <groupId>org.springframework.boot</groupId>
23            <artifactId>spring-boot-autoconfigure</artifactId>
24            <version>${spring-boot.version}</version>
25        </dependency>
26        <dependency>
27            <groupId>org.springframework.boot</groupId>
28            <artifactId>spring-boot-configuration-processor</artifactId>
29            <version>${spring-boot.version}</version>
30        </dependency>
31        <dependency>
32            <groupId>commons-net</groupId>
33            <artifactId>commons-net</artifactId>
34            <version>${commons-net.version}</version>
35        </dependency>
36        <dependency>
37            <groupId>org.slf4j</groupId>
38            <artifactId>log4j-over-slf4j</artifactId>
39            <version>${slf4j.version}</version>
40        </dependency>
41        <dependency>
42            <groupId>org.slf4j</groupId>
43            <artifactId>slf4j-api</artifactId>
44            <version>${slf4j.version}</version>
45        </dependency>
46    </dependencies>
47
48</project>
49

3 使用

将 starter 打包到本地 maven 仓库,在项目中引用即可。如果不配置用户名或密码,则以匿名方式连接 FTP 服务器,否则,用户名/密码方式连接 FTP 服务器。


标题:封装ftp-spring-boot-starter并实现文件上传
作者:kangaroo1122
地址:https://www.kangaroohy.com/articles/2021/02/23/1614070843844.html
声明:如非特别说明,版权归kangaroo1122 所有,转载请注明出处,谢谢!
签名:No pains, no gains.