Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

352
Views
How to attach Media to a Facebook Post using the API

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!