Search code examples
csvmultipartform-datadataweavemulesoftmule4

How to work with CSV file from multipart/form-data POST request in Mulesoft


I am submitting a POST request from Postman to a Mulesoft endpoint and the payload is multipart/form-data. The payload has two files, one is a pdf and the other is a CSV. This is what the CSV part of the payload looks like in DataWeave

{
  headers: {
    "Content-Disposition": {
      name: "testData",
      filename: "CSV Data.csv",
      subtype: "form-data"
    },
    "Content-Type": "text/csv"
  },
  content: [] as Array {raw: "SU5WMTIzNCxQTzEyMzQsMTIzNCwxLzEvMjAyNCw0MzIxDQo=" as Binary {base: "64"}, mediaType: "text/csv", mimeType: "text/csv"}
}

How do I get the actual CSV values and convert it to perhaps JSON?

I've tried using "Transform Message" with the output set as "application/dw" but it didn't seem to work.

Please advise,


Solution

  • It is a bit unclear how that request was made but the content is a CSV that has been encoded in Base64 but for some reason it is presented as an array of bytes. You could try getting the raw content this way (change the path from the top of the multi part payload),

    payload.content.^raw as String
    

    Then you can read the output of that expression as a CSV, and map as needed:

    %dw 2.0
    output application/json
    ---
    read(payload.content.^raw as String, "application/csv",{header:false})
        map {
            a: $[0],
            b: $[1],
            c: $[2],
            d: $[3]
        }
    

    Output:

    [
      {
        "a": "INV1234",
        "b": "PO1234",
        "c": "1234",
        "d": "1/1/2024"
      }
    ]