I found the following in Posting to a Chatter Feed using the Cross-Domain XHR client side proxy support.
var sr = JSON.parse('<%=signedRequestJson%>');
// Reference the Chatter user's URL from Context.Links object.
var url = sr.context.links.chatterFeedsUrl+"/news/"+sr.context.user.userId+"/feed-items";
var body = {body : {messageSegments : [{type: "Text", text: "Some Chatter Post"}]}};
Sfdc.canvas.client.ajax(url,
{client : sr.client,
method: 'POST',
contentType: "application/json",
data: JSON.stringify(body),
success : function(data) {
if (201 === data.status) {
alert("Success");
}
}
});
Of note is how it does a more RAW AJAX POST to via the Canvas API in JavaScript.
With this, the problem is how to do a multipart/form-data POST via the Canvas ajax method. The Chatter API: Examples, Best Practices and Tips links to an example multipart POST.
The source for the Canvas ajax method is on GitHub.
Try switching out the JSON.stringify(body)
with the FormData instance.
At a very high level:
- Add the first FormData for the normal JSON body. Se the Content-Type to application/json. See Composing multipart/form-data with a different Content-Type on each parts with Javascript
- Append the next FormData entry for the attachment with the correct Content-Type.
- Use the FormData as the
data
parameter to the Ajax request.
From Sending multipart/formdata with jQuery.ajax:
I'm aware that a the jQuery ajax method is a very different thing to the canvas ajax method, but it might provide some clues in the right direction around using the FormData.
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});