Multipart Form Handling

Not applicable

Hello All,

Does anyone have any sample code on handling/parsing multipart data in Apigee? Just looking for something simple which handles a value from a HTML text field *and* a HTML file upload (for our purposes, something simple like a JPG).

TIA

- Steve

3 1 1,104
1 REPLY 1

Not applicable

Here is a bit of JSC that demonstrates a way to get to the multipart data. This method populates a flow variable with a JSON representation of the various elements submitted. It is lightly tested and is intended as a proof of concept only:

var body = context.getVariable("request.content"),
    formBoundary = context.getVariable("request.header.Content-Type"),
    result = {
        resultCount: 0,
        results: []
    };

if (formBoundary.indexOf("multipart/form-data") === 0) {
    //per RFC2046:5.1
    formBoundary = '--' + formBoundary.split('=')[1];
    var bodySegments = body.split(formBoundary);

    bodySegments.forEach(function(segment) {
        var lines = segment.split('\r\n'),
            res = {};
        lines.forEach(function(line) {
            if ((line.indexOf('Content-Disposition:') === 0) || (line.indexOf('Content-Type:') === 0)) {
                //handle the nv pairs here
                var pairs = line.split(';');
                pairs.forEach(function(pair) {
                    var nvPair = pair.split('=');
                    if (nvPair.length == 1) nvPair = pair.split(': ');
                    res[nvPair[0].trim()] = nvPair[1].trim();
                });
            } else {
                if (!res.value) res.value = line;
                else res.value += line;
            }
        });
        if (res.value !== '--' && res.name) {
            result.resultCount++;
            result.results.push(res);
        }
    });
}

context.setVariable("result", JSON.stringify(result));

The output of this function will be something like this:

{
  "resultCount": 2,
  "results": [
    {
      "value": "---snip binary data---",
      "Content-Disposition": "form-data",
      "name": "\"submittedFile\"",
      "filename": "\"18152d2.jpg\"",
      "Content-Type": "image/jpeg"
    },
    {
      "value": "formValue",
      "Content-Disposition": "form-data",
      "name": "\"formName\""
    }
  ]
}