I need to know how to upload a directory to remote server and download a directory from remote server using sftp-spring boot with spring integration.
I can upload and download the file . but I cannot able to upload a folder (entire directory) . I want to upload entire directory which has sub directory also and the same for download thing.
This is my code for download a file from remote server.
@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;
}
It works for download a file from remote server. but I need to download a directory along with sub directory from remote server using spring integration.
Thanks in advance...
CodePudding user response:
if you know this directory, for example "/home/user/myFiles/image.png" if you don't know the path you can split directories via "/" like that inputDirectory.split("/") and work with the list of directories
use these methods in ChannelSftp class:
- cd("/") method to access road directory
- mkdir("folderName") to create a new folder (surround it with try and catch because it will give an exception if the folder already exists)
- put(InputStream src, String fileName, SftpProgressMonitor monitor, int mode) to upload the file
- get(fileName) to download the file
and read this tutorial: https://www.baeldung.com/java-file-sftp
CodePudding user response:
The MessageSource
impls for remote files don't support recursive fetching yet: https://github.com/spring-projects/spring-integration/issues/3407.
However you can use an SftpOutboundGateway
with its MGET
(or LS
) command support and RECURSIVE
option.
See more in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/sftp.html#using-the-ls-command