You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Integration中传递InputStream至FTP出站适配器的实现问题

问题

需要将PDFBox生成并转换为InputStream的PDF文件上传至FTP服务器,已编写以下Spring Integration代码,但不清楚如何将InputStream数据传递给FTP出站适配器:

@Bean
public IntegrationFlow localToFtpFlow() {
    return IntegrationFlows.from("toFtpChannel")
            .handle(Ftp.outboundAdapter(sf())
                    .remoteDirectory("/ftp/forklift_checklist"))
            .get();
}

@MessagingGateway
public interface MyGateway {

    @Gateway(requestChannel = "toFtpChannel")
    void sendToFtp(InputStream file);

}
解决方案

Spring Integration的FTP出站适配器无法直接处理裸InputStream,需要在消息中同时传递流数据和远程文件名,具体调整如下:

  1. 修改网关方法,添加文件名消息头
    通过@Header注解指定目标文件名,让FTP适配器明确要保存的文件格式和名称。

  2. 配置FTP适配器优化传输(可选)
    添加useTempFileName(false)配置,适配器会直接使用指定的文件名上传,避免生成临时文件的额外步骤。

修正后的完整代码:

import org.springframework.integration.file.FileHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;

// 省略其他必要导入

@Bean
public IntegrationFlow localToFtpFlow() {
    return IntegrationFlows.from("toFtpChannel")
            .handle(Ftp.outboundAdapter(sf())
                    .remoteDirectory("/ftp/forklift_checklist")
                    .useTempFileName(false)) // 可选,直接以目标文件名上传
            .get();
}

@MessagingGateway
public interface MyGateway {

    @Gateway(requestChannel = "toFtpChannel")
    void sendToFtp(@Payload InputStream file, @Header(FileHeaders.FILENAME) String fileName);

}

使用方式

调用网关时,传入PDFBox生成的InputStream和指定的PDF文件名(例如"forklift_checklist.pdf"):

// 假设pdfInputStream是PDFBox生成的PDF输入流
myGateway.sendToFtp(pdfInputStream, "forklift_checklist.pdf");

如果不使用网关,也可以直接构建Message对象发送到通道:

import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

// ...

Message<InputStream> ftpMessage = MessageBuilder.withPayload(pdfInputStream)
        .setHeader(FileHeaders.FILENAME, "forklift_checklist.pdf")
        .build();
toFtpChannel.send(ftpMessage);

内容的提问来源于stack exchange,提问作者Elias Khattar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:05:25