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,需要在消息中同时传递流数据和远程文件名,具体调整如下:
修改网关方法,添加文件名消息头
通过@Header注解指定目标文件名,让FTP适配器明确要保存的文件格式和名称。配置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
相关产品推荐
相关产品推荐

