Search code examples
mulemultipart

How to pass multipart/related request in Mule?


I want to request an API using Mule.It is using Multipart/related Content-Type to upload a file.I Don't know how to pass the boundary information in mule.How to set the given input in a payload to send to HTTP.I tried to put it in a transform Message component but it showing errors. enter image description here

enter image description hereenter image description here


Solution

  • You can use the outbound attachments collection to create the form parts as necessary, and don't need to specify the boundary.

    For example, consider the following Mule configuration:

    <scripting:component doc:name="Groovy">
      <scripting:script engine="Groovy"><![CDATA[
        message.addOutboundAttachment('some-json.json', '{ "name": "My File" }', 'application/json');
        message.addOutboundAttachment('myfile.txt', new java.io.File('c:\\myfile.txt'), null);
      ]]></scripting:script>
    </scripting:component>
    <http:request config-ref="HTTP_Request_Configuration" path="/" method="POST" doc:name="HTTP"/>
    

    The outbound HTTP request which Mule issues is:

    POST / HTTP/1.1
    Host: localhost:80
    User-Agent: AHC/1.0
    Connection: keep-alive
    Accept: */*
    Content-Type: multipart/form-data; boundary=pHSj1qavizuHBv879Hoo_RQ9tFqtAfS9i;charset=UTF-8
    Content-Length: 438
    
    --pHSj1qavizuHBv879Hoo_RQ9tFqtAfS9i
    Content-Disposition: form-data; name="some-json.json"
    Content-Type: application/json
    Content-Transfer-Encoding: binary
    
    { "name": "My File" }
    --pHSj1qavizuHBv879Hoo_RQ9tFqtAfS9i
    Content-Disposition: form-data; name="myfile.txt"; filename="myfile.txt"
    Content-Type: text/plain
    Content-Transfer-Encoding: binary
    
    This is just some random text file...
    
    --pHSj1qavizuHBv879Hoo_RQ9tFqtAfS9i--
    

    Hope that helps.