I am trying to post multipart/form-data using Mule ESB but cannot get it to work. I have the same request working successfully through my rest client and cURL.
curl -i -X POST \
-H "Authorization:bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \
-H "X-ANYPNT-ORG-ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \
-H "X-ANYPNT-ENV-ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \
-H "Content-Type:multipart/form-data" \
-F "artifactName=test" \
-F "targetId=xxxxxx" \
-F "file=@\"./test-1.0.0-SNAPSHOT.zip\";type=application/x-zip-compressed;filename=\"test-1.0.0-SNAPSHOT.zip\"" \ 'https://anypoint.mulesoft.com/hybrid/api/v1/applications'
I am using a Transformer to add the outbound attachments;
message.setPayload(NullPayload.getInstance());
message.addOutboundAttachment("artifactName", AttachmentHelper.getStringAttachment("artifactName", artifactName));
message.addOutboundAttachment("targetId", AttachmentHelper.getStringAttachment("targetId", targetId.toString()));
message.addOutboundAttachment("file", AttachmentHelper.getURLAttachment("file", file));
public class AttachmentHelper {
public static DataHandler getStringAttachment(String name, String value) {
logger.info("Adding string attachment " + name + ": " + value);
byte[] bytes = value.getBytes();
return new DataHandler(new ByteArrayDataSource(bytes, "text/plain", name));
}
public static DataHandler getURLAttachment(String name, String value) throws Exception {
InputStream is = new URL(value).openStream();
byte[] bytes = IOUtils.toByteArray(is);
return new DataHandler(new ByteArrayDataSource(bytes, "application/x-zip-compressed", name));
}
}
Then just making the service call;
<http:request method="POST" path="/hybrid/api/v1/applications" config-ref="http_request_mule" doc:name="POST Deploy Application Call">
<http:request-builder>
<http:header headerName="Authorization" value="bearer #[sessionVars.token]" />
<http:header headerName="X-ANYPNT-ORG-ID" value="#[sessionVars.orgId]" />
<http:header headerName="X-ANYPNT-ENV-ID" value="#[sessionVars.envId]" />
<http:header headerName="Content-Type" value="multipart/form-data" />
</http:request-builder>
</http:request>
I am getting an HTTP Status 400 back and I can see when I comment out the HTTP call the request is not formed correctly;
Unexpected character (-) at position 0.
--null
Content-Type: application/x-zip-compressed
C:\DEV\zips\test-1.0.0-SNAPSHOT.zip (byte content removed for post)
--null
Content-Type: text/plain
xxxxxx (value correct here just masked)
--null
Content-Type: text/plain
test
--null--
It appears to be failing to add the content-disposition, attachment name and the filename.
I have tried just about everything and read just about everything and am at a loss. Any ideas?
Solved! The only change I had to make to get it working is to add the filename;