Camel Rest DSL retrieve HTTP POST multipart File

后端 未结 1 1452
清歌不尽
清歌不尽 2021-01-14 05:02

My Router class looks like below and i am trying to upload a video file and store it to a File location.

SpringBootRouter.java

packa         


        
相关标签:
1条回答
  • 2021-01-14 06:03

    You can use MimeMultipartDataFormat to unmarshal Multipart request. Using this, will prepare attachments, to Exchange.

    After that you need somehow convert Attachment to InputStream and fill CamelFileName header. With this task can help you small Processor.

    Route:

    from("direct:upload")
            .unmarshal().mimeMultipart().split().attachments()
            .process(new PrepareFileFromAttachment())
            .to("file://C:/RestTest");
    

    Processor:

    class PrepareFileFromAttachment implements Processor {
        @Override
        public void process(Exchange exchange) throws Exception {
            DataHandler dataHandler = exchange.getIn().getBody(Attachment.class).getDataHandler();
            exchange.getIn().setHeader(Exchange.FILE_NAME, dataHandler.getName());
            exchange.getIn().setBody(dataHandler.getInputStream());
        }
    }
    

    The approach above does not work in case your form contains only single input in form. This is because MimeMultipartDataFormat marshals first form input into body (without storing file name) and other inputs to attachments where the file name is stored. In this case you need to create Processor reading InputStream directly:

    Route:

    from("direct:upload")
            .process(new ProcessMultipartRequest())
            .to("file:c://RestTest");
    

    Processor

    public class ProcessMultipartRequest implements Processor {
        @Override
        public void process(Exchange exchange) throws Exception {
            InputStream is = exchange.getIn().getBody(InputStream.class);
            MimeBodyPart mimeMessage = new MimeBodyPart(is);
            DataHandler dh = mimeMessage.getDataHandler();
            exchange.getIn().setBody(dh.getInputStream());
            exchange.getIn().setHeader(Exchange.FILE_NAME, dh.getName());
        }
    }
    
    0 讨论(0)
提交回复
热议问题