Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (11.9k points)

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 binary 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 fell 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 Salesforces.

1 Answer

0 votes
by (32.1k points)
edited by

To manually organize a multipart/form request body that includes the binary, and that bypass the standard UTF-8 encoding done by browsers. This is done by passing the entire request as an ArrayBuffer.

Here's the code you could use to resolve this problem

 // {

//   Body: base64EncodedData,

//   ContentType: '',

//   Additional attachment info (i.e. ParentId, Name, Description, etc.)

// }

function uploadAttachment (objectData, onSuccess, onError) {

    // Define a boundary

    var boundary = 'boundary_string_' + Date.now().toString();

    var attachmentContentType = !app.isNullOrUndefined(objectData.ContentType) ? objectData.ContentType : 'application/octet-stream';

// Serialize the object, excluding the body, which will be placed in the second partition of the multipart/form-data request

var serializedObject = JSON.stringify(objectData, function (key, value) { return key !== 'Body' ? value : undefined; });

var requestBodyBeginning = '--' + boundary

    + '\r\n'

    + 'Content-Disposition: form-data; name="entity_attachment";'

    + '\r\n'

    + 'Content-Type: application/json'

    + '\r\n\r\n'

    + serializedObject

    + '\r\n\r\n' +

    '--' + boundary

    + '\r\n'

    + 'Content-Type: ' + attachmentContentType

    + '\r\n'

    + 'Content-Disposition: form-data; name="Body"; filename="filler"'

    + '\r\n\r\n';

var requestBodyEnd =

    '\r\n\r\n'

    + '--' + boundary + '--';

// The atob function will decode a base64-encoded string into a new string with a character for each byte of the binary data.

var byteCharacters = window.atob(objectData.Body);

// Each character's code point (charCode) will be the value of the byte.

// We can create an array of byte values by applying .charCodeAt for each character in the string.

var byteNumbers = new Array(byteCharacters.length);

for (var i = 0; i < byteCharacters.length; i++) {

    byteNumbers[i] = byteCharacters.charCodeAt(i);

}

// Convert into a real typed byte array. (Represents an array of 8-bit unsigned integers)

var byteArray = new Uint8Array(byteNumbers);

var totalRequestSize = requestBodyBeginning.length + byteArray.byteLength + requestBodyEnd.length;

var uint8array = new Uint8Array(totalRequestSize);

var i;

// Append the beginning of the request

for (i = 0; i < requestBodyBeginning.length; i++) {

    uint8array[i] = requestBodyBeginning.charCodeAt(i) & 0xff;

}

// Append the binary attachment

for (var j = 0; j < byteArray.byteLength; i++, j++) {

    uint8array[i] = byteArray[j];

}

// Append the end of the request

for (var j = 0; j < requestBodyEnd.length; i++, j++) {

    uint8array[i] = requestBodyEnd.charCodeAt(j) & 0xff;

}

return $j.ajax({

    type: "POST",

    url: salesforceUrl,

    contentType: 'multipart/form-data' + "; boundary=\"" + boundary + "\"",

    cache: false,

    processData: false,

    data: uint8array.buffer,

    success: onSuccess,

    error: onError,

    beforeSend: function (xhr) {

        // Setup OAuth headers...

    }

});

};

Want to get certified in Salesforce? Here is the Salesforce Online Training you are looking for!

Browse Categories

...