Search code examples
springspring-integrationspring-integration-sftp

Spring SFTP - Upload file with different name


I am using spring to upload file to remote server. I am able to upload local file with same name in remote server. Now, I want to upload local file (example - test.txt) with different name (example - test_20180601.txt) into remote server. I am using below code now. How can I modify this code to change file name?

@Configuration
@EnableConfigurationProperties(GcaSftpConfig.class)
@ConditionalOnProperty(prefix = "sftp.gca", name = "active", matchIfMissing = true)
public class GcaSftpUploadProcess 
{
    @Autowired
    private GcaSftpConfig config;

    @Bean(name = "gcaUploadSftpSessionFactory")
    public SessionFactory<LsEntry> sftpSessionFactory() 
    {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost(config.getUpload().getHost());
        factory.setPort(config.getUpload().getPort());
        factory.setUser(config.getUpload().getUser());
        factory.setPassword(config.getUpload().getPassword());
        factory.setTimeout(config.getUpload().getTimeout());
        factory.setAllowUnknownKeys(true);
        return factory;
     }

    @Bean(name = "gcaUploadSftpRemoteFileTemplate")
    public SftpRemoteFileTemplate sftpRemoteFileTemplate() throws Exception
   {
        SftpRemoteFileTemplate template = new SftpRemoteFileTemplate(sftpSessionFactory());
        template.setRemoteDirectoryExpression(new LiteralExpression(config.getUpload().getRemoteDirectory()));
        template.afterPropertiesSet();      
        return template;
    }

    public void upload(String localFileNameWithPath)
    {
        File file = new File(localFileNameWithPath);
        Message<File> message = MessageBuilder.withPayload(file).build();
        String send = sftpRemoteFileTemplate().send(message, FileExistsMode.REPLACE);       
    }
}

Solution

  • The RemoteFileTemplate has this option:

    /**
     * Set the file name generator used to generate the remote filename to be used when transferring
     * files to the remote system. Default {@link DefaultFileNameGenerator}.
     * @param fileNameGenerator the file name generator.
     */
    public void setFileNameGenerator(FileNameGenerator fileNameGenerator) {