Handling File Attachments: Handling Multipart Requests in Mule
Join the DZone community and get the full member experience.Join For Free
If I were to do this back in the days where I didn’t know about such a thing called “Mule”, I would have needed to:
- Handle a http multipart stream
- Identify all the parts in the message
- Read each file
- Clean up
Of course there’re libraries and frameworks that can help you with this, but all of them still require some level of understanding of the multipart request beneath.
And then came Mule into my life, and this task became as simple as navigating the properties of a MuleMessage interface. Let’s explain a little bit….
As you probably know, what the MuleESB does is to carry packages of information (messages) from one system to another, allowing for software integration without the need of the involved systems to know about each other, their transport, protocols or any API changes. Each of those packages of information are represented by a MuleMessage. This object acts as a facade to access of a great deal of information about the message including, headers, payload and attachments, but today I want to focus on a property called inbound attachments.
When the message is coming through an http post that sends N >= 1 files through a Multipart Request, each of those files will be automatically read by Mule and stored in the message under the inboundAttachments property.
Pretty cool uh? No more worrying about Multipart, streams or anything like it, you just need to access this property as a Key-Value pair where the key is the filename and the value is the content itself. MuleMessage also provides a getInboundAttachmentNames() that returns all the keys.
So, let’s see a couple of examples. Suppose you want to retrieve the content of an expected file named foo.txt:
Now, let’s suppose that you want a flow that receives N >= 1 amount of attachments and logs all of them:
<flow name="multi-attachment-exampleFlow1" doc:name="multi-attachment-exampleFlow1"> <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" doc:name="HTTP"/> <foreach collection="#[message.inboundAttachments]" doc:name="Foreach"> <logger message="#[message.inboundAttachments[payload]]" level="ERROR" doc:name="Logger"/> </foreach> </flow>
That was easy wasn’t it? If you’re thinking that this is pretty
simple stuff compared to the average post in this blog, then mission
accomplished! We have succeeded in demonstrate how easy it is to do
every day chores using Mule. Please let us know if this post makes your
life easier, that would really make us happy.
Published at DZone with permission of Mariano Gonzalez, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.