使用FtpOutboundGateway按特定文件名下载文件

时间:2018-03-27 14:52:08

标签: spring-boot spring-integration spring-rest

我使用Spring启动服务从ftp服务器下载单个基于模式的文件。模式中的文件名根据客户端的请求参数而变化。并且文件不应该保存在本地。

我是新手,我无法找到关于如何使用FtpOutboundGateway和Java配置实现此目的的良好解释。请帮忙。

以下是一些示例,以显示我在这方面采取的措施:

FtpOutboundGateway bean:

@Bean
@ServiceActivator(inputChannel = "requestChannel")
public FtpOutboundGateway ftpFileGateway() {
    FtpOutboundGateway ftpOutboundGateway =
                      new FtpOutboundGateway(ftpSessionFactory(), "get", "'Ready_Downloads/'");
    ftpOutboundGateway.setOptions("-P -stream");
    ftpOutboundGateway.setOutputChannelName("downloadChannel");
    return ftpOutboundGateway;
}

在服务端点中使用自动装配的OutboundGateway ftpFileGateway bean:

@RequestMapping(value="/getFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] downloadFile(@RequestPart Map<String, String> fileDetails) throws Exception
{
    String filename = fileDetails.get("filename");

        FtpSimplePatternFileListFilter filter = new FtpSimplePatternFileListFilter( "*"+filename+"*");
        ftpFileGateway.setFilter(filter);

        //then what?...
}

我假设我可能需要使用输入和输出消息通道,但不确定如何继续。

1 个答案:

答案 0 :(得分:0)

您不应该为每个请求改变网关;它不是线程安全的。

根本不需要过滤器;只需发送fileName作为发送到get网关的消息的有效负载,并将网关表达式设置为...

new FtpOutboundGateway(ftpSessionFactory(), "get", 
    "'Ready_Downloads/' + payload"

修改

@SpringBootApplication
public class So49516152Application {

    public static void main(String[] args) {
        SpringApplication.run(So49516152Application.class, args);
    }

    @Bean
    public ApplicationRunner runner (Gate gate) {
        return args -> {
            InputStream is = gate.get("bar.txt");
            File file = new File("/tmp/bar.txt");
            FileOutputStream os = new FileOutputStream(file);
            FileCopyUtils.copy(is, os);
            System.out.println("Copied: " + file.getAbsolutePath());
        };
    }

    @ServiceActivator(inputChannel = "ftpGet")
    @Bean
    public FtpOutboundGateway getGW() {
        FtpOutboundGateway gateway = new FtpOutboundGateway(sf(), "get", "'foo/' + payload");
        gateway.setOption(Option.STREAM);
        return gateway;
    }

    @Bean
    public DefaultFtpSessionFactory sf() {
        DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
        sf.setHost("...");
        sf.setUsername("...");
        sf.setPassword("...");
        return sf;
    }

    @MessagingGateway(defaultRequestChannel = "ftpGet")
    public interface Gate {

        InputStream get(String fileName);

    }

}