skip to Main Content

I’m working on a React project with Facebook user integration.
I need to post a client-side generated image to a private group on behalf of the logged-in user.
Using the {group-id}/photo endpoint I can successfully post a picture which already exists on the web providing the url and caption parameters:

const postImageUrlToFacebook = () => {
    const url = "https://upload.wikimedia.org/wikipedia/commons/e/e0/New.gif";
    let caption = "test upload url image from React";
    httpFacebookGraphClient(facebookToken)
      .post("/" + ldlTestFacebookGroupId + "/photos", { url, caption })
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  };

The definition of the httpFacebookGraphClient is the following:

import axios, { AxiosRequestConfig } from "axios";

const httpFacebookGraphClient = (token: string | null) => {
  const defaultOptions = {
    baseURL: "https://graph.facebook.com/v14.0",
    method: "get",
    // withCredentials: true,
    headers: {
      "Content-Type": "application/json",
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the access token parameter for any request
  instance.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
    if (!config) {
      config = {};
    }
    if (!config.params) {
      config.params = {};
    }
    config.params.access_token = token;
    config.params.limit = "999";
    return config;
  });

  return instance;
};

export default httpFacebookGraphClient;

I would now need to start from a default svg, modifiy some g tags inside of it via javascript, convert to jpg and post it to a facebook group.
Let’s suppose the starting SVG is the following:

<svg id="Livello_1" data-name="Livello 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 107"><defs><style>.cls-1,.cls-3,.cls-4,.cls-5{fill:#ffc000;}.cls-2{fill:#fff;}.cls-3,.cls-4,.cls-5{stroke:#fff;stroke-miterlimit:10;}.cls-3{stroke-width:0.87px;}.cls-4{stroke-width:0.79px;}.cls-5{stroke-width:0.65px;}</style></defs><title>bannerino scegli il tuo sconto</title><path class="cls-1" d="M136.88,2.63a10,10,0,0,1,10,10V94.37a10,10,0,0,1-10,10H13.13a10,10,0,0,1-10-10V12.63a10,10,0,0,1,10-10H136.88m0-2H13.13a12,12,0,0,0-12,12V94.37a12,12,0,0,0,12,12H136.88a12,12,0,0,0,12-12V12.63a12,12,0,0,0-12-12h0Z"/></svg>

I started from the end, trying to post a local image to the Facebook group before trying to build the image, but I’m already stuck.
Reading the Facebook api docs at this link I found this sentence on the url parameter;

The URL of a photo that is already uploaded to the Internet. You must specify this or a file attachment

mentioning a file attachment.

Again on the Facebook docs I found this that explain how to upload a file to Facebook to use it in subsequent api calls, but I can’t make it to work.

Anyone could give me a hint on how to proceed?

2

Answers


  1. Chosen as BEST ANSWER

    I found the way around this and I can successfully post an image selected by input field client side.

    React component state:

     const [fileToUpload, setFileToUpload] = useState<any>();
    

    inputFileChangeHandler:

      const inputFileChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.currentTarget != null && event.currentTarget.files != null) {
          setFileToUpload(event.currentTarget.files[0]);
        }
      };
    

    uploadImageToFacebook:

      const uploadImageToFacebook = () => {
        let caption = "test upload local image from React";
        const fileReader = new FileReader();
        fileReader.onloadend = async () => {
          if (fileReader.result != null) {
            const photoData = new Blob([fileReader.result], { type: "image/png" });
            const formData = new FormData();
            formData.append("source", photoData);
            formData.append("caption", caption);
            httpFacebookGraphClient(facebookToken)
              .post("/" + ldlTestFacebookGroupId + "/photos", formData, {
                headers: {
                  "Content-Type": "multipart/form-data",
                },
              })
              .then((res) => {
                console.log(res.data);
              })
              .catch((err) => {
                console.log(err);
              });
          }
        };
        fileReader.readAsArrayBuffer(fileToUpload);
      };
    

    On jsx:

    <input type="file" id="file-input" onChange={inputFileChangeHandler} />
    <button onClick={uploadImageToFacebook}>Invia</button>
    

  2. @marcob8986

    I am having the same issue, but I am using PHP instead JS. For some reason the post doesn’t publish the image, only the caption… Do you know how can I solve this?

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v17.0/'.$id_group.'/photos');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'access_token' => $token,
        //'source' => file_get_contents($imagemPath),
        'url' => 'https://scripts.linkasites.com.br/gerador-de-post/times/sao-paulo/imagens-posts/post-gente-como-a-gente-lucas-comemora-vaga-na-final-em-hamburgueria-paulistana.jpg',
        'caption' => $caption,
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    //    'Content-Type: multipart/form-data'
    //));
    
    $result = curl_exec($ch);
    curl_close($ch);
    
    echo $result;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search