I'm trying to upload Image to wordpress using Wordpress rest API.
Everything is working but, proper image is not getting uploaded. However, when i use Curl image is proper.
curl --request POST \
--url http://localhost/wordpress/wp-json/wp/v2/media/ \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=hh.jpg" \
--header "authorization: Basic token" \
--header "content-type: image/jpg" \
--data-binary "@C://Users/as/Desktop/App _Ideas/hh.jpg" \
This curl request is working properly.
Now, when i converted request to Nodejs
request({
url: ' http://localhost/wordpress/wp-json/wp/v2/media/',
headers: {
'cache-control': 'no-cache',
'content-disposition': 'attachment; filename='+filename,
'content-type' : 'image/jpg',
'authorization' : 'Basic token'
},
encoding: null,
method: 'POST',
body: "@C://Users/as/Desktop/App _Ideas/hh.jpg",
encoding: null
}, (error, response, body) => {
if (error) {
res.json({name : error});
} else {
res.json(JSON.parse(response.body.toString()));
}
});
I'm able to receive json response from wordpress as imge uploaded. But, uploaded image is not proper as binary data passed was not proper.
Wordpress uploades folder shows file hh.jpg
for size 17 bytes.. On editing with notepad it show @hh.jpg
which means string data is saved as hh.jpg not the actual binary data.
Any ideas how to pass binary data properly with Nodejs.
Got it working , We need to create a stream of file using
fs.createReadStream(filename);
fs module.
request({
url: 'http://localhost/wordpress/wp-json/wp/v2/media/',
method: 'POST',
headers: {
'cache-control': 'no-cache',
'content-disposition': 'attachment; filename=' + filename,
'content-type' : 'image/jpg',
'authorization' : 'Basic token'
},
encoding: null,
body: fs.createReadStream('C://Users/as/Desktop/App _Ideas/hh.jpg')
}, (error, response, body) => {
if (error) {
res.json({name : error});
} else {
res.json(JSON.parse(response.body.toString()));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With