NodeJs send Binary Data with Request

时间:2018-02-26 17:51:17

标签: node.js

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 个答案:

答案 0 :(得分:1)

搞定了,我们需要使用

创建一个文件流
fs.createReadStream(filename);

fs模块。

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