1
votes

how to upload media-image or featured-image in wordpress using rest api.

I've created new post using WordPress REST API, and now I am uploading Image to my Wordpress Site using REST API but i am unable to achieve it due to error "No data Supplied" kindly please Check Screenshot

enter image description here

which is the best way to create new post in WordPress with Featured Image, right now in my mind

  1. Upload Media File to WordPress Site and Get Media ID
  2. Create New Post with Media ID
2
I dont see images so I added a complete code in answerDlk

2 Answers

2
votes

you almost right, just lack media(image) raw binary data.

for python, using code:

import requests

toUploadImagePath = "/xxx/xxx.jpg"
mediaImageBytes = open(toUploadImagePath, 'rb').read()
# b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\.....'

uploadImageFilename = "661b943654f54bd4b2711264eb275e1b.jpg"
curHeaders = {
  "Authorization": "Bearer xxx.yyy.zzz-xxx-yyy-zzz",
  "Content-Type": "image/jpeg",
  "Accept": "application/json",
  'Content-Disposition': "attachment; filename=%s" % uploadImageFilename,
}

resp = requests.post(
  "https://www.crifan.com/wp-json/wp/v2/media",
  headers=curHeaders,
  data=mediaBytes,
)

full code can refer my lib: crifanWordpress.py

and my Chinese post: 【已解决】用Python通过WordPress的REST API上传图片 (will publish in short future)

1
votes

Using the REST API to upload a file to WordPress is quite simple. All you need is to send the file in a POST-Request to the wp/v2/media route.

UPDATED added data response true

$file = file_get_contents( 'test.jpg' );
$url = 'http://example.com/wp-json/wp/v2/media/';
$ch = curl_init();
$username = 'admin';
$password = 'password';

curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
    'Content-Disposition: form-data; filename="example.jpg"',
    'Authorization: Basic ' . base64_encode( $username . ':' . $password ),
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );

MORE https://gist.github.com/ahmadawais/0ccb8a32ea795ffac4adfae84797c19a