Rocko
Rocko

Reputation: 166

400 Bad Request error with HTTP multipart request

I am trying to hit 1 API, making an HTTP POST request using multipart data, but I am getting 400 Bad Request Error.

var reqPayload='{
    "param1":"value1"
}';

var ajaxOptions = {
            url: href,
            type: method_NAME,
            async: true
};
ajaxOptions.data = new FormData();
ajaxOptions.data.append("jsonInputParameters", $.parseJSON(reqPayload));

ajaxOptions.contentType = false;
ajaxOptions.processData = false;

//following will not create any problem since there is only 1 file.
$.each($('#id_NAME input[type="file"]')[0].files, function(i, file) {
    ajaxOptions.data.append('primaryFile', file);
});

My request looks like this:

------WebKitFormBoundary9hoSobTAHgGksFST
Content-Disposition: form-data; name="jsonInputParameters"

[object Object]
Content-Disposition: form-data; name="primaryFile"; filename="example.txt"
Content-Type: text/plain

------WebKitFormBoundary9hoSobTAHgGksFST

But, what I want is this:

------WebKitFormBoundary9hoSobTAHgGksFST
Content-Disposition: form-data; name="jsonInputParameters"

{
"parentID":"FB4CD874EF94CD2CC1B60B72T0000000000100000001"
}

------WebKitFormBoundary9hoSobTAHgGksFST
Content-Disposition: form-data; name="primaryFile"; filename="example.txt"
Content-Type: text/plain

<File Content>
------WebKitFormBoundary9hoSobTAHgGksFST--

Please let me know some work-around to issue this problem.

Upvotes: 1

Views: 1349

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

Your reqPayload variable is a string, so you don't need to serialise it at all; you can just append it to the FormData as-is:

ajaxOptions.data.append("jsonInputParameters", reqPayload);

That said, it's much better practice, and easier to maintain, if you create the payload as an object and then use JSON.stringify to serialise the data before making the request, like this:

var reqPayload = {
    param1: "value1"
};
ajaxOptions.data.append("jsonInputParameters", JSON.stringify(reqPayload));

Upvotes: 1

Related Questions