繁体   English   中英

如何使用 spring 与 sftp 集成上传和下载目录及其子目录

[英]How to upload and download a directory along with sub directory using spring integration with sftp

我需要知道如何使用带有 spring 集成的 sftp-spring 引导将目录上传到远程服务器并从远程服务器下载目录。

我可以上传和下载文件。 但我无法上传文件夹(整个目录)。 我想上传整个目录,它也有子目录,下载的东西也一样。

这是我从远程服务器下载文件的代码。

 @Bean
 public DefaultSftpSessionFactory getSftpSessionFactory()
{
    DefaultSftpSessionFactory defaultSftpSessionFactory=new 
    DefaultSftpSessionFactory();
    defaultSftpSessionFactory.setHost("hostName");
    defaultSftpSessionFactory.setPort(22);
    defaultSftpSessionFactory.setAllowUnknownKeys(true);
    defaultSftpSessionFactory.setUser("root");
    defaultSftpSessionFactory.setPassword("12qwaszx");
    return defaultSftpSessionFactory;
}

@Bean(name="mydefaultSync")
public SftpInboundFileSynchronizer synchronizer()
{
    SftpInboundFileSynchronizer synchronizer=new 
   SftpInboundFileSynchronizer(getSftpSessionFactory());
    synchronizer.setDeleteRemoteFiles(true);
    synchronizer.setRemoteDirectory("/root/upload/");
    synchronizer.setFilter(new 
    SftpSimplePatternFileListFilter("*.txt"));
    return synchronizer;

}

@Bean(name="stfpServer")
@InboundChannelAdapter(channel="fileDownload", 
 poller=@Poller(fixedDelay = "3000"))
public MessageSource<File> sftpMessageSources()
{
    SftpInboundFileSynchronizingMessageSource source=new SftpInboundFileSynchronizingMessageSource(synchronizer());
    source.setLocalDirectory(new File("download/"));
    source.setAutoCreateLocalDirectory(true);
    source.setMaxFetchSize(1);
    return source;
}

它适用于从远程服务器下载文件。 但我需要使用 spring 集成从远程服务器下载一个目录和子目录。

提前致谢...

远程文件的MessageSource impls 尚不支持递归获取: https://github.com/spring-projects/spring-integration/issues/3407

但是,您可以使用SftpOutboundGateway及其MGET (或LS )命令支持和RECURSIVE选项。

在文档中查看更多信息: https://docs.spring.io/spring-integration/docs/current/reference/html/sftp.html#using-the-ls-command

如果您知道此目录,例如“/home/user/myFiles/image.png”,如果您不知道路径,则可以通过“/”拆分目录,例如 inputDirectory.split("/") 并使用目录列表

在 ChannelSftp class 中使用这些方法:

  1. cd("/") 方法访问道路目录
  2. mkdir("folderName") 创建一个新文件夹(用 try 和 catch 包围它,因为如果该文件夹已经存在它会给出一个异常)
  3. put(InputStream src, String fileName, SftpProgressMonitor monitor, int mode) 上传文件
  4. get(fileName) 下载文件

并阅读本教程: https://www.baeldung.com/java-file-sftp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM