File upload and additional fields via multipart/form-data

Since the original thread was closed and i was struggling for hours finding a solution so I would like to present my solution to you. Requirement: Had to upload a PDF document and send a JSON string to an API endpoint and was facing 400 Bad Request and 415 Unsupported Media Type. Since http request nodes uses nodejs form-data library to perform multipart/form-data request i came up with the options argument. These arguments allows to specify additional properties to each boundary

msg.headers = {
    "Content-Type": "multipart/form-data",
};
msg.payload = {
    "file": {
        "value": FILECONTENT,
        "options": {
            "filename": FILENAME,
            "contentType": 'application/pdf',
        }
    },
    "json":{
        "value": "{"property": "value"}",
        "options": {
            "contentType": 'application/json',
        }
    } 
}

Leads to (example manually created):

------WebKitFormBoundaryL1mYuhVxLFBNwBTF
Content-Disposition: form-data; name="file"; filename="FILENAME"
Content-Type: application/pdf

FILECONTENT
------WebKitFormBoundaryL1mYuhVxLFBNwBTF
Content-Disposition: form-data; name="json";
Content-Type: application/json

{"property": "value"}
------WebKitFormBoundaryL1mYuhVxLFBNwBTF--

Cheers

Stefan

1 Like

Thank you for this example, It helped me to learn more about HTTP requests and headers.

1 Like