Over a million developers have joined DZone.

Multiple Attachments in MuleSoft

DZone's Guide to

Multiple Attachments in MuleSoft

In this post, a Mule-based developer shows us how we can handle attachments in MuleSoft, using the example of sending attachments to REST/SOAP API.

· Integration Zone ·
Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

This article is all about how we can handle multiple attachments in MuleSoft.

Let's say we have a requirement to send attachments to a REST/SOAP API.

In order to achieve this one can follow the below steps:

1. Declare a variable which can store a list.    

<set-variable variableName="attachments" value="#[new.java.util.ArrayList()]" doc:name="attachments">

2. Use a foreach scope in order to handle multiple attachments and read attachments using the transform-message component. Add each attachment to the array list. 

<foreach collection="#[message.inboundAttachments]" doc:name="For Each">
<dw:transform-message doc:name="Read Attachment">
          %dw 1.0
          %output application/java
          "fileName": payload.dataSource.part.fileName,
          "filedata": payload.inputStream,
          "fileSize": payload.dataSource.part.size
<expression-transformer expression="#[flowVars.attachments.add(payload)]" doc:name="Add attachment to List">

If you want to send an encoded string instead of a byte array, you can define a global function and use it as below:

<configuration doc:name="Configuration">
def byteToEncodedString(bytes) {
import org.apche.commons.codec.binary.Base64;
import java.lang.String;
byte[] encoded = Base64.encodeBase64(bytes);
String encoString = new String(encoded);
return encodedString;

Use the above global function in DataWeave:

          %dw 1.0
          %output application/java
          "fileName": payload.dataSource.part.fileName,
          "filedata": byteToEncodedString(payload.inputStream),
          "fileSize": payload.dataSource.part.size

Set payload with value = flowVars.attachments.

Now if you have any specific request format for an API, you can easily transform the current payload in the required format using a Transform Message component.

Download A Buyer's Guide to Application and Data Integration, your one-stop-shop for research, checklists, and explanations for an application and data integration solution.

mulesoft ,integration ,rest api ,soap api

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}