How to add a content type to a multipart query without using Blob

I communicate with Salesforce through their REST API via JavaScript. They expect the format of the request body 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

In the code below, I got the request body very close to their expected format, except that it does not include the Content-Type (application / json) in the first border.

// 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 the content type for serialized JSON in the first border. It's necessary; in fact, through Fiddler, I was able to confirm that when the Content-Type text exists in the first section of the border, the request handles just fine.

I tried the following, which treats the serialized JSON as bind data, in order to be able to provide a content type:

formData.append("entity_attachment", new Blob([JSON.stringify({ data: '' })], { "type": "application/json"}));

      

This gives the following HTTP:

Content-Disposition: form-data; name="entity_attachment"; filename="blob"
Content-Type: application/json
...

      

Unfortunately, the Salesforce server provides the following error message:

Cannot include more than one binary part

      

The last way I can think of formatting my data in a specific Salesforce body format is to manually create the request body; I tried to do this, but I was embarrassed trying to concatenate the binary, which I'm not sure about how to concatenate the string.

I am looking for any suggestions to get my request body to match Salesforce.

+3


source to share


1 answer


This answer shows how to manually create a multipart / form request body that includes a binary and bypasses the standard UTF-8 encoding performed by browsers. This is done by passing the entire request as an ArrayBuffer.

Here is the code I am using to solve the problem (see this answer ):



    // {
//   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 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...
    }
});

      

};

+4


source







All Articles