Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP Rest API upload image

Tags:

I'm trying to upload image via Wordpress REST api v2. So far all I managed was to create empty entries in wordpress media library. Meaning they have image names, but no actual image.

POST Request:

http://localhost/wordpress/wp-json/wp/v2/media

Authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==
Content-Type: application/json
Content-Disposition: attachment;filename=map2.jpg

{
  "source_url" : "file:///C:/Users/x/Desktop/map2.jpg"
}

Response:

{
  "id": 127,
  "date": "2016-05-25T08:43:30",
  "date_gmt": "2016-05-25T08:43:30",
  "guid": {
    "rendered": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
    "raw": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg"
  },
  "modified": "2016-05-25T08:43:30",
  "modified_gmt": "2016-05-25T08:43:30",
  "password": "",
  "slug": "map2-3",
  "status": "inherit",
  "type": "attachment",
  "link": "http://localhost/wordpress/map2-3/",
  "title": {
    "raw": "map2-3",
    "rendered": "map2-3"
  },
  "author": 1,
  "comment_status": "open",
  "ping_status": "closed",
  "alt_text": "",
  "caption": "",
  "description": "",
  "media_type": "image",
  "mime_type": "image/jpeg",
  "media_details": {},
  "post": null,
  "source_url": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
  "_links": {
    "self": [
      {
        "href": "http://localhost/wordpress/wp-json/wp/v2/media/127"
      }
    ],
    "collection": [
      {
        "href": "http://localhost/wordpress/wp-json/wp/v2/media"
      }
    ],
    "about": [
      {
        "href": "http://localhost/wordpress/wp-json/wp/v2/types/attachment"
      }
    ],
    "author": [
      {
        "embeddable": true,
        "href": "http://localhost/wordpress/wp-json/wp/v2/users/1"
      }
    ],
    "replies": [
      {
        "embeddable": true,
        "href": "http://localhost/wordpress/wp-json/wp/v2/comments?post=127"
      }
    ]
  }
}

I get no errors, everything's seem to be working, except response->post and response->media_details is either null or empty. Ofcourse image itself is not uploaded.

Based on this GitHub WP-API Adding Media ticket, I should send 2 requests. First POST request should return data with post object. I would send this post object via PUT method, and image should be uploaded...since I have no post object, this is not possible.

Any ideas what am I doing wrong?

like image 948
CrazySabbath Avatar asked May 25 '16 08:05

CrazySabbath


People also ask

Is it possible to add media upload to WordPress REST API?

WordPress REST APIis quite interesting especially when you are trying to update the website from some third-party resources. Recently I had to implement a similar feature where most of the things like custom post type, taxonomyetc. worked as they should except images. So, here I’m going to show how I made the media upload part work.

How to sideload images in WordPress using the API?

Sideloading images is not supported by the wordpress api so you will have to do some changes. First, your content-type should be image/jpeg and not application/json, remember that content-type is supposed to reflect the data that you are passing and the POST media request expects an image.

Can I see the information returned through the REST API?

If you var_dumpthe response from the first request, you can see all the information returned through the API. Reply seponsays: March 28, 2021 at 12:58 am I want to Upload image use wordpress REST api via Android. please help me Reply Leave a comment Cancel reply Your email address will not be published. Required fields are marked * Comment Name *

How do I upload media to a POST endpoint?

So first upload the media to endpoint POST /wp-json/wp/v2/media, with the following HTTP headers and the file contents as data: The catch here was the Content-Disposition header. This call should return the media ID, which you will need now for calling POST /wp-json/wp/v2/posts/ {$existingPostId}.


2 Answers

Sideloading images is not supported by the wordpress api so you will have to do some changes.

First, your content-type should be image/jpeg and not application/json, remember that content-type is supposed to reflect the data that you are passing and the POST media request expects an image.

Another change you have to make to accommodate the content-type is the way that you are passing the data. Instead of sending it with the source_url parameter, try passing it as a binary file.

One last thing I would mention is that the wp/v2 calls return 3XX status on a few occasions. It would be useful to follow those redirects and redo those requests to those new urls.

I had some issues passing JPEG images but PNG images have worked well. Here is a curl example that I use to upload png media:

curl --request POST \
--url http://www.yoursite.com/wp-json/wp/v2/media \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=tmp" \
--header "authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==" \
--header "content-type: image/png" \
--data-binary "@/home/web/tmp.png" \
--location
like image 168
ren.rocks Avatar answered Sep 19 '22 16:09

ren.rocks


My working answer using PHP cUrl

<?php

$curl = curl_init();

$data = file_get_contents('C:\test.png');

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://woo.dev/wp-json/wp/v2/media",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_HTTPHEADER => array(
    "authorization: Basic XxxxxxxXxxxxXx=",
    "cache-control: no-cache",
    "content-disposition: attachment; filename=test.png",
    "content-type: image/png",
  ),
  CURLOPT_POSTFIELDS => $data,
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
like image 41
Ayman Magedy Avatar answered Sep 20 '22 16:09

Ayman Magedy