views:

426

answers:

4

How can I do multipart file uploads using the Apache Camel HTTP component ?

A: 

Does it have to be using Camel?

Apache Fileupload does this quite simply http://commons.apache.org/fileupload/using.html

JoseK
Yes, it has to be camel. Also, Apache Fileupload is a server side component. I need to upload files from camel to a server that already knows how to process multi part uploads. I've resorted to encapsulating the upload part in a separate bean. It would have been nice though to have it work out of the box.
bunting
+2  A: 

I don't know is it possible to send multipart forms using the HTTP component.

If you need the workaround, you can create POJO Spring Bean that uses the Apache Http Client (and its MultipartPostMethod). Then you can route your message to that bean:

from("activemq:uploadQueue").to("bean:myApacheHttpClientBean?method=sendMultiPart")
Henryk Konsek
Thanks, that's what I've essentially done. It works now.
bunting
A: 

Could you please provide more details how do you want multipart form reach apache camel?

Should it be some form on a webpage that send directly to Camel route? Or AMQ queue? I'd suggest you checking Apache HTTP and Apache Jetty components.

archer
A: 

As long as your message body is in multipart/form-data format, you can use the Camel http component to POST it to another server. The trick is to set your Content-Type properly and set the request method to be POST:

<route>
  <from uri="direct:start"/>
  <setBody>
    <![CDATA[
    --__MyCoolBoundary__
    Content-Disposition: form-data; name="name"

    Paul Mietz Egli
    --__MyCoolBoundary__
    Content-Disposition: form-data; name="email"

    [email protected]
    --__MyCoolBoundary__--
    ]]>
  </setBody>
  <setHeader headerName="Content-Type">
    <constant>multipart/form-data; boundary="__MyCoolBoundary__"</constant>
  </setHeader>
  <setHeader headerName="CamelHttpMethod">
    <constant>POST</constant>
  </setHeader>
  <to uri="http://www.example.com/mywebservice.php"/&gt;
</route>

Obviously, the example body above isn't that useful because it's all static data. There are a number of ways you can construct the body -- I've used XSLT outputting in text mode, a scripted expression (e.g. <groovy>...</groovy>), and a Spring bean. XSLT works well when your incoming message body is already an XML document:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
<xsl:template match="/">
--__MyCoolBoundary__
Content-Disposition: form-data; name="name"

<xsl:value-of select="//name"/>
--__MyCoolBoundary__--
</xsl:stylesheet>

You do need to be careful about extra whitespace, however. Hope this helps!

pegli