javascriptfacebookfacebook-graph-apifacebook-javascript-sdkfacebook-social-plugins

How to post local images to Facebook via JavaScript SDK without URL?


I am trying to use the JSSDK for a desktop website, not a mobile website. I am able to login, and then here is what I am doing:

  1. Enable user to login with app_id, and get access_token.
  2. Get a local image's base64 data (its a constraint) and turn that to a blob.
  3. Send an upload request with this blob as image "source" So by the docs I am expected to get an "id" if successful, along with redirection to the post url.

Here's my snippet:

//2.
function base64ToBlob(base64String) {
    const parts = base64String.split(',');
    const header = parts[0];
    const encodedData = atob(parts[1]);
    const buffer = new Uint8Array(encodedData.length);
    for (let i = 0; i < buffer.length; i++) {
        buffer[i] = encodedData.charCodeAt(i);
    }

    return new Blob([buffer], { type: header.replace(/data:([^;]*);base64,/, '$1') });
}

//3.
async function handleUpload(accessToken, blob) {
    const formData = new FormData();
    formData.append('source', blob);
    formData.append('access_token', accessToken);
    formData.append('caption', 'test_photo_upload');
    
    try {
         const response = await fetch('https://graph.facebook.com/v19.0/me/photos', {
             method: 'POST',
             body: formData,
        });
    
        const data = await response.json();

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}, ${JSON.stringify(data.error)}`);
        console.log('Photo uploaded successfully:', data);
             return data;
        } catch (error) {
             console.error('Error uploading photo:', error);
             return null
        }
   }

It says the endpoint has deprecated due to the related permissions having been deprecated.

enter image description here


Solution

  • So it turns out that the permission "publish_permission" and its dependent endpoints were stated to be deprecated long since 2018 and done for in 2020. Instead of continuing this question I will ask a new one for what the current method is.

    Article for this deprecation: https://developers.facebook.com/blog/post/2018/07/31/platform-update-publish-permission/

    Here's a related answer on stack: Facebook Graph API SDK v5 - Publishing a picture to a page's Album

    The official docs should have stated this as deprecated. Instead we get this in the form of error message. Nvm.