SpringBoot集成ftp

2024-05-29  本文已影响0人  爱的旋转体

1、添加maven依赖

        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-ftp</artifactId>
            <version>${spring-integration.version}</version>
        </dependency>

2、ftp配置

ftp:
  host: 
  port: 
  username:
  password: 
package com.xzp.config;

import cn.hutool.core.util.ObjectUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Map;
import java.util.Optional;

@Data
@ConfigurationProperties(prefix = "ftp")
public class FtpProperties {
    private String host;
    private Integer port;
    private String username;
    private String password;
    private String remoteDirectory = "";
    private String temporaryFileSuffix = ".tmp";
    private Boolean useTemporaryFileName = true;
    private Boolean autoCreateDirectory = true;
    private Integer clientMode = 0;
    private String controlEncoding = "UTF-8";

    public Integer getClientMode() {
        return Optional.ofNullable(clientMode).orElse(0);
    }

}
package com.xzp.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.file.remote.RemoteFileTemplate;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.ftp.session.DefaultFtpSessionFactory;
import org.springframework.integration.ftp.session.FtpRemoteFileTemplate;

import javax.annotation.Resource;

@ConditionalOnProperty(
        prefix = "ftp",
        value = {"host","port","username","password"}
)
@EnableConfigurationProperties(FtpProperties.class)
@Configuration
public class FtpConfiguration {

    public static final String REMOTE_FILE_TEMPLATE_BEAN_NAME = "remoteFileTemplate";

    @Resource
    private FtpProperties ftpProperties;

    @Bean
    public SessionFactory<FTPFile> ftpSessionFactory() {
        DefaultFtpSessionFactory factory = new DefaultFtpSessionFactory();
        factory.setHost(ftpProperties.getHost());
        factory.setPort(ftpProperties.getPort());
        factory.setUsername(ftpProperties.getUsername());
        factory.setPassword(ftpProperties.getPassword());
        factory.setClientMode(ftpProperties.getClientMode());
        if(StringUtils.isNotBlank(ftpProperties.getControlEncoding())){
            factory.setControlEncoding(ftpProperties.getControlEncoding());
        }
        return new CachingSessionFactory<>(factory);
    }

    @Bean(REMOTE_FILE_TEMPLATE_BEAN_NAME)
    public RemoteFileTemplate<FTPFile> remoteFileTemplate(){
        RemoteFileTemplate<FTPFile> template = new FtpRemoteFileTemplate(ftpSessionFactory());
        template.setRemoteDirectoryExpression(new LiteralExpression(ftpProperties.getRemoteDirectory()));
        template.setTemporaryFileSuffix(ftpProperties.getTemporaryFileSuffix());
        template.setUseTemporaryFileName(ftpProperties.getUseTemporaryFileName());
        template.setAutoCreateDirectory(ftpProperties.getAutoCreateDirectory());
        return template;
    }

}

3、封装方法

package com.xzp.service;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.file.remote.RemoteFileTemplate;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Objects;

@SuppressWarnings("all")
@Slf4j
@Component
public class FtpService {

    @Autowired(required = false)
    private RemoteFileTemplate<FTPFile> remoteFileTemplate;

    /**
     /**
     * 上传文件
     *
     * @param localFilePath 本地文件路径
     * @param remoteFileDir 远程文件目录
     * @return true-成功,false-失败,null-没有开启ftp
     */
    public Boolean upload(String localFilePath, String remoteFileDir) {
        if(Objects.isNull(remoteFileTemplate)){
            return null;
        }
        Assert.notBlank(localFilePath, "本地文件路径不能为空");
        Assert.notBlank(remoteFileDir, "远程文件目录不能为空");
        log.info("上传文件到ftp, localFilePath:[{}], remoteFileDir:[{}]", localFilePath, remoteFileDir);
        remoteFileDir = remoteFileDir.endsWith(File.separator) ? remoteFileDir : remoteFileDir + File.separator;
        try {
            Message<File> message = MessageBuilder.withPayload(new File(localFilePath)).build();
            String result = remoteFileTemplate.send(message, remoteFileDir);
            log.info("上传文件到ftp, 响应结果:[{}]", result);
            return true;
        } catch (Exception e) {
            log.error("上传文件到ftp异常, localFilePath:[{}], remoteFileDir:[{}], 异常信息:[{}]", localFilePath, remoteFileDir, e.getMessage(), e);
            return false;
        }
    }

    public Boolean removeDir(String remoteFileDir){
        try {
            if(Objects.isNull(remoteFileTemplate)){
                return null;
            }
            FTPFile[] list = remoteFileTemplate.list(remoteFileDir);
            if(ArrayUtils.isNotEmpty(list)){
                for (FTPFile ftpFile : list) {
                    if(ftpFile.isDirectory()){
                        removeDir(remoteFileDir + File.separator + ftpFile.getName());
                    }else{
                        remoteFileTemplate.remove(remoteFileDir + File.separator + ftpFile.getName());
                    }
                }
            }
            remoteFileTemplate.getSession().rmdir(remoteFileDir);
            return true;
        } catch (Exception e){
            log.error("删除ftp文件夹异常,异常信息:[{}]",e.getMessage(),e);
            return false;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读