Search code examples
spring-integration

Multipart Returns Bytes or InputStream not sure how to upload it to FTP server


Below is the code where we have multipart object - which will have either bytes or input stream

    Map<String, MultipartFile> multipartRequestParams = request.getFileMap();
    MultipartFile multipartFile = multipartRequestParams.get("file");
    multipartFile.getBytes() (or) multipartFile.getInputStream

How to define a gateway for this and send the file

     gateway.upload(multipartFile.getBytes(), multipartFile.getOriginalFilename(), remoteDirectory); 

        @MessagingGateway
    public interface UploadGateway {
        @Gateway(requestChannel = "toSftpChannel")
        void upload(@Payload byte[] file, @Header("filename") String filename, @Header("path") String path);
    }

    @Bean
    @ServiceActivator(inputChannel = "toSftpChannel")
    public MessageHandler toHandler() {
    ....
    ....
    }

I'm confused how to send this file to the SFTP server via which mechanism?


Solution

  • multipartFile.getBytes() (or) multipartFile.getInputStream

    That's not true. The byte array in this case is really extracted from that InputStream. So, according your description both of them are present at the same time.

    The rest of your code is OK. That's is fully correct to have a byte arrays (or that file InputStream) as a @Payload and other useful data as @Header.

    To transfer that data into SFTP you should use an SftpMessageHandler, which support both byte[] and InputStream as a payload of request message from that toSftpChannel. See more info in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/sftp.html#sftp-outbound.

    The filename header could be used from the setFileNameGenerator(FileNameGenerator fileNameGenerator) option of that SftpMessageHandler. You just take this header from a message provided for that FileNameGenerator contract.

    Similar could be done for the path header, which, essentially, should lend in the setRemoteDirectoryExpressionString(String remoteDirectoryExpression) option, like this setRemoteDirectoryExpressionString("headers.path").

    All that info is present in the mentioned docs.