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:
我通过JavaScript通过REST API与Salesforce进行通信。他们希望multipart / form-data内容类型的请求体格式非常具体:
--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
如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.
通过下面的代码,我得到了请求体非常接近它们的预期格式,除了它在第一个边界中不包含Content-Type(application / json)。
// 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.
此代码不会将序列化JSON的内容类型放在第一个边界中。这是必要的;事实上,通过Fiddler,我能够确认当第一个边界部分中存在Content-Type文本时,请求处理得很好。
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:
我尝试执行以下操作,将序列化的JSON视为绑定数据,并提供提供内容类型的能力:
formData.append("entity_attachment", new Blob([JSON.stringify({ data: '' })], { "type": "application/json"}));
This yields the following HTTP:
这会产生以下HTTP:
Content-Disposition: form-data; name="entity_attachment"; filename="blob"
Content-Type: application/json
...
Unfortunately, Salesforce server gives the following error message:
不幸的是,Salesforce服务器给出以下错误消息:
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.
我可以想到将数据格式化为特定Salesforce体格式的最后一种方法是手动构建请求体;我试图这样做,但我觉得连接二进制文件很短暂,我不确定如何在字符串中连接。
I'm looking for any suggestions to get my request body to match Salesforce's.
我正在寻找任何建议让我的请求机构与Salesforce相匹配。
1 个解决方案
#1
4
This answer shows how to manually build a multipart/form request body that includes the binary, and that bypasses the standard UTF-8 encoding done by browsers. This is done by passing the entire request as an ArrayBuffer.
这个答案显示了如何手动构建包含二进制文件的多部分/表单请求主体,并绕过浏览器完成的标准UTF-8编码。这是通过将整个请求作为ArrayBuffer传递来完成的。
Here's the code I'm using to resolve the problem (as seen in 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'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...
}
});
};
#1
4
This answer shows how to manually build a multipart/form request body that includes the binary, and that bypasses the standard UTF-8 encoding done by browsers. This is done by passing the entire request as an ArrayBuffer.
这个答案显示了如何手动构建包含二进制文件的多部分/表单请求主体,并绕过浏览器完成的标准UTF-8编码。这是通过将整个请求作为ArrayBuffer传递来完成的。
Here's the code I'm using to resolve the problem (as seen in 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'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...
}
});
};