WP Rest API Media Upload is Successful But Returns 500 Error

Question

I was able to successfully upload an image via the WP Rest API using the following code:

        $this->guzzle_client->post( $this->trailingSlashIt( $this->url ) . $this->api_medias_endpoint, [
            'auth'        => [ $this->username, $this->password ],
            'headers'     => [
                'cache-control' => 'no-cache',
                'Content-Disposition' => 'attachment; filename="'.basename($from_media_path).'"',
                'content-type' => $mime,
            ],
            'body' => $content,
        ] );

However, it returns a 500 error every time so an Exception is thrown and I catch it of course:

        catch ( Exception $ex ) {
           $res = json_decode($ex->getResponse()->getBody());
           if(is_array($res) && isset($res[0]->id)){
               return $res[0];
           }

           logger( 'upload media ERROR' );
           logger($ex->getMessage());
           logger($ex->getTraceAsString());
           return false;
       }

I retrieve the server response and return it to the calling code. But this is not how it’s supposed to be. Why is it returning a 500 error when the image upload is successful? What should be done here?

By the way, I tried it via cURL and the same thing happens. Upload is successful (image will be found in Media) but call will return a 500 error. Here is the code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'cache-control: no-cache',
    'Content-Disposition: attachment; filename="test.jpg"',
    'content-type: image/jpeg',
));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$html = trim(curl_exec($ch));
curl_close($ch);

return $html;

Anyone have any ideas?

Thanks!

0
Paolo 2 months 0 Answers 11 views 0

Leave an answer