I am composing an image in a canvas, I get the base64 image data by using canvas.toDataURL('png') and trimming the additional information.
var dataUrl = canvas.toDataURL('png');
var escapedBase64Data = dataUrl.replace("data:image/png;base64,","");
After that I try to post to facebook using:
FB.api('/me/photos', 'post', { source:data});
Photos (https://developers.facebook.com/docs/reference/api/user/) has a source property. This is where you will place the data content (multipart/form-data) of your photo.
I convert my base64 encoded data to multipart/form-data by specifying the headers.
The result looks like this:
--0.2242348059080541
Content-Disposition: file; name="file"; filename="image.png"
Content-Type: image/png
Content-Transfer-Encoding: base64
iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t+KAAAbBElEQVR4Xu3dP4jre0LG4V2xsFVYEKy
...
QAAAABJRU5ErkJggg==
--0.2242348059080541--
After I complete the FB api call I receive the following error:
Object {message: "(#324) Requires upload file", type: "OAuthException", code: 324}
Any suggestions?
Thanks
解决方案
Here a working code example :
var boundary = '----ThisIsTheBoundary1234567890';
var formData = '--' + boundary + '\r\n'
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
for (var i = 0; i < imageData.length; ++i)
{
formData += String.fromCharCode(imageData[ i ] & 0xff);
}
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += f.message + '\r\n'
formData += '--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true);
xhr.onload = xhr.onerror = function() {
// error managment
};
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
//Send the request
xhr.sendAsBinary(formData);