通过Graph API将本地图片发布到facebook群组

问题描述 投票:0回答:2

我正在开发一个与 Facebook 用户集成的 React 项目。 我需要代表登录用户将客户端生成的图像发布到私人组。 使用

{group-id}/photo
端点,我可以成功发布网络上已存在的图片,并提供
url
caption
参数:

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);
      });
  };

httpFacebookGraphClient 的定义如下:

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;

我现在需要从默认的 svg 开始,通过 javascript 修改其中的一些 g 标签,转换为 jpg 并将其发布到 Facebook 群组。 假设起始 SVG 如下:

<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>

我从最后开始,尝试在尝试构建图像之前将本地图像发布到 Facebook 群组,但我已经陷入困境。 在这个link阅读Facebook api文档,我在

url
参数上找到了这句话;

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

提及文件附件

再次在 Facebook 文档上我发现 this 解释了如何将文件上传到 Facebook 以在后续 api 调用中使用它,但我无法使其工作。

任何人都可以给我一个如何继续的提示吗?

reactjs facebook facebook-graph-api axios multipartform-data
2个回答
0
投票

我找到了解决这个问题的方法,我可以成功发布由输入字段客户端选择的图像。

反应组件状态:

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

输入文件更改处理程序:

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

上传图片至Facebook:

  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);
  };

在 jsx 上:

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

0
投票

@marcob8986

我有同样的问题,但我使用 PHP 而不是 JS。由于某种原因,该帖子没有发布图像,只发布了标题...你知道我该如何解决这个问题吗?

$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;
© www.soinside.com 2019 - 2024. All rights reserved.