Home > Mobile >  How to attach Media to a Facebook Post using the API
How to attach Media to a Facebook Post using the API

Time:10-10

I have followed the Facebook documentation to request access token and post to a Facebook Page.

Now, I wish to create a post and attach some photos to that post but Facebook is only posting the text body and not including the photo files.

Here is how I did it:

   ...
    let mediaIds = [];
    for (let photoUrl of photoUrls) {
        let mediaUploadUrl = `https://graph.facebook.com/${pageId}/photos?url=${photoUrl}&access_token=${pageAccessToken}`;
        let response = await axios.post(mediaUploadUrl);
        let { id } = response.data;
        if (id) {
            mediaIds.push(id);
        }
    }

    // Now that we have the mediaIds, let's attach them to the post as below:

    let urlParams = new URLSearchParams();
    urlParams.append("access_token", pageAccessToken);
    urlParams.append("message", "Hello World");
    
    let postUrl = `https://graph.facebook.com/${pageId}/feed`;

    if (mediaIds.length > 0) {
        for (let i = 0; i < mediaIds.length; i  ) {
            let mediaId = mediaIds[i];
            let mediaIdObject = { media_fbid: mediaId };
            urlParams.append(`attached_media[${i}]`, mediaIdObject);
        }
    }
    
    try {
        let { data } = await axios.post(postUrl, urlParams);
        let postId = data.id;
    } catch (e) {
        done = false;
        console.log(e); //An unknown error has occurred is the error message I keep getting
    }
    ...

All I keep getting in return is

An unknown error has occurred

But if I go to the Facebook Page, I noticed the text body was posted but not the photo attachments.

Any ideas on fixing this would be really appreciated.

CodePudding user response:

Appending an object to urlParams, as you do in

let mediaIdObject = { media_fbid: mediaId };
urlParams.append(`attached_media[${i}]`, mediaIdObject);

produces a URL parameter like

attached_media[0]=[object Object]

Use

urlParams.append(`attached_media[${i}]`, JSON.stringify(mediaIdObject));

instead.

  • Related