Facebook's Graph API (v2.5) User Photo Edge says that there are two separate ways of publishing photos to Facebook:
1: Attach the photo as multipart/form-data. The name of the object doesn't matter, but historically people have used source as the parameter name for the photo.How this works depends on the SDK you happen to be using to do the post.
2: Use a photo that is already on the internet by publishing using the url parameter:
FB.api(
"/me/photos",
"POST",
{
"url": "{image-url}"
},
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
I need to use the first method (multipart) as I have got the base64 image data from canvas.
This seems to be confusing as I don't find the documentation very informative. I understand that the urlData of image is to be encoded in some format in the multipart data along with other parameters. I fail to find any working sample code/proper explanation on how to do this using Javascript SDK & graph api v2.5; even after an exhaustive search on stackoverflow. I have seen a various partially answered/unanswered questions regarding this on stackoverflow...But I still fail to get it work.
Please help. Thanks !
Similar Questions
Facebook Javascript Form Data Photo Upload: requires upload file error
Javascript: Upload image from Canvas to FB via Graph API
Upload Base64 Image Facebook Graph API - Not clear if Javascript Api has been here
[Edit] - Code I have already tried.
var ctx = document.getElementById('canvas2');
urldata=ctx.toDataURL("image/png");
FB.api('/photos', 'POST', {
message: 'testing Graph API',
access_token: accessToken,
url: urldata,
no_story:true
}, function (response) {
if (!response || response.error) {
console.log('Error occured:' + response.error.message);
} else {
alert('Post ID: ' + response.id);
}
}
);
Response -" Error occured:(#324) Missing or invalid image file "
I was not able to use the JS SDK with this, but it works with a simple AJAX request (with the Fetch API, axios or something else).
First, turn the Canvas Image into a Blob with the following function:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
After that, you can use the blog with FormData:
formData.append('source', blob);
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/