简体   繁体   中英

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 .

Will recommend to use PHP SDK for such operations. https://github.com/facebook/facebook-php-business-sdk


    $account = new \FacebookAds\Object\AdAccount('Your ID');
    assert($account instanceof \FacebookAds\Object\AdAccount);
    $account->createAdImage(['array of fields'],['array of request Params'],);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM