Search code examples
phplaravelfacebookfacebook-graph-apifacebook-php-sdk

The provided image file is invalid. Please check your image path again. Facebook Graph Api error


I am trying to upload image to Facebook graph api with Http Client of Laravel. But I am getting the error mentioned before.

    $ad_account_id = env("AD_ACCOUNT_ID");
    $access_token = env("ACCESS_TOKEN");
    $image = $request->file('image');

    $response = Http::asForm()
        ->withHeaders(['Content-Type: multipart/form-data'])
        ->post('https://graph.facebook.com/v14.0/act_' . $ad_account_id . '/adimages',
            [
                'filename' => file_get_contents($image),
                'access_token' => $access_token
            ]
        );

    dd(json_decode($response->body()));

In documentation Facebook gives me curl api example like this

curl \
  -F 'filename=@<IMAGE_PATH>' \
  -F 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v<API_VERSION>/act_<AD_ACCOUNT_ID>/adimages

Problem is all about IMAGE_PATH. I have tried to send any kind of path of uploaded image even in base64 format. I am able to upload the same image with same api in Postman. There is not any problem about access_token or ad_account_id.


Solution

  • Solved my problem by using attach method of HTTP client:

    $ad_account_id = env("AD_ACCOUNT_ID");
    $access_token = env("ACCESS_TOKEN");
    $image = $request->file('image');
    
    $response = Http::attach('filename', file_get_contents($image), 'image.jpg')
        ->post('https://graph.facebook.com/v14.0/act_' . $ad_account_id . '/adimages',
            [
                'access_token' => $access_token
            ]
        );
    
    dd(json_decode($response->body()));