0

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?

marcob8986
  • 153
  • 4
  • 12
  • 1
    "or a file attachment" simply means a standard HTTP file upload. The parameter name doesn't even matter, AFAIK, choosing that is up to you – CBroe Aug 23 '22 at 06:14

1 Answers1

0

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>
marcob8986
  • 153
  • 4
  • 12
  • Hello @marcob8986 I am facing the same issue, but I am using PHP instead JS, do you know how can I solve this? sending the image src link with link parameter, doesnt works ;( – Sophie Aug 18 '23 at 20:56