I'm communicating with Salesforce through their REST API via JavaScript. They expect the request body format for the multipart/form-data content-type to be very specific:
--boundary_string
Content-Disposition: form-data; name="entity_document";
Content-Type: application/json
{
"Description" : "Marketing brochure for Q1 2011",
"Keywords" : "marketing,sales,update",
"FolderId" : "005D0000001GiU7",
"Name" : "Marketing Brochure Q1",
"Type" : "pdf"
}
--boundary_string
Content-Type: application/pdf
Content-Disposition: form-data; name="Body"; filename="2011Q1MktgBrochure.pdf"
Binary data goes here.
--boundary_string--
As seen at https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm
Through the below code, I've gotten the request body very close to their expected format, except that it doesn't include the Content-Type (application/json) in the first boundary.
// Prepare binary data
var byteString = window.atob(objectData.Body);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], { "type": "image/png" });
// Setup form
var formData = new FormData();
formData.append("entity_attachment", JSON.stringify({ data: '' }));
formData.append("Body", bb);
var request = new XMLHttpRequest();
request.open("POST", myurl);
request.send(formData);
This code will not put a content-type for the serialized JSON in the first boundary. This is needed; in fact, through Fiddler, I was able to confirm that when the Content-Type text exists in the first boundary section, the request is processed just fine.
I tried to do the following, which treats the serialized JSON as bindary data, with the benefit of giving the ability to provide the content type:
formData.append("entity_attachment", new Blob([JSON.stringify({ data: '' })], { "type": "application/json"}));
This yields the following HTTP:
Content-Disposition: form-data; name="entity_attachment"; filename="blob"
Content-Type: application/json
...
Unfortunately, Salesforce server gives the following error message:
Cannot include more than one binary part
The last way I can think of formatting my data into the specific Salesforce body format, is to manually build up the request body; I tried to do this, but I felt short on attempting to concatenate the binary, which I am unsure in how to concatenate in a string.
I'm looking for any suggestions to get my request body to match Salesforce's.