Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Camel multipart HTTP post (file upload)

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

like image 692
Kai Sternad Avatar asked Mar 10 '10 09:03

Kai Sternad


2 Answers

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")
like image 174
Henryk Konsek Avatar answered Oct 31 '22 12:10

Henryk Konsek


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"/>
</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">
<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!

like image 3
pegli Avatar answered Oct 31 '22 13:10

pegli