Skip to content Skip to sidebar Skip to footer

Node Js How To Post Image Along With Request Data To Another Server/api

I am trying to POST an image from my Node JS app to another REST API. I have the image in Mongo DB (as binary array data) that is read by Node JS and then is supposed to be POSTed

Solution 1:

if you have control over "the other API" too, you could include the image as base64 representation of the binary data in the post-body (and decode it on the API side)

answer to the update 06/06/2017:

according to the screenshot the API requires multipart/formdata. such requests with the "request"-module are documented in https://github.com/request/request#multipartform-data-multipart-form-uploads

quick example (not tested):

var formData = {
  Data: {data: {client: "abc" ...},
  file: fs.createReadStream('testImage_2.jpg'),
};
request.post({url:'<YourUrl>', formData: formData}, functionoptionalCallback(err, httpResponse, body) {
  if (err) {
    returnconsole.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});

Solution 2:

If you add the body to your request with the JSON data, you should be able to send it:

var options = {
        host: 'hostname.com',
        port: 80,
        path: '/api/content',
        method: 'POST',
        headers:{
            'Content-Type' : 'multipart/form-data'
        },
        body: {
            "data": {"client":"abc","address": "123"},
            "meta":{"owner": "yourself","host": "hostishere"}
        }
 };

What I don't understand is why you have a setTimeout with res.send when there is no res variable defined anywhere.

Post a Comment for "Node Js How To Post Image Along With Request Data To Another Server/api"