4
votes

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.

1
Yeah.... The body you pass is a string. I guess @path is curl's syntactic sugar. - Alex Michailidis
@alex-rokabilis yes you are right. On editing the uploaded image with notepad it show hh.jpg means the string is saved as image due to content-disposition header. - Atul Sharma
Any ideas how to upload it correctly ? - Atul Sharma
Yeah, try body: require('fs').createReadStream("C://Users/as/Desktop/App _Ideas/hh.jpg") ( I am not sure about the correct format of paths in windows, maybe you need backslashes?) - Alex Michailidis

1 Answers

12
votes

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