F
F
felsme2020-06-22 00:20:02
Node.js
felsme, 2020-06-22 00:20:02

How to convert image to form-data in Node.js?

How to convert an image to form-data and send it in a post request via request?
the code:

let fd = new FormData()
fd.append('file', fs.createReadStream('ddd.jpg'), 'ddd.jpg')
                

                let form = {
                    "photo": fd
                }

                let headers = {
                    "Content-Type": "multipart/form-data",
                }


                request.post({
                    url: data.response.upload_url,
                    form: form,
                    headers: headers

                }, (a,b,c) => {
                    console.log(c)
                })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergei Chamkin, 2020-06-22
@felsme

Request generated in Postman

var request = require('request');
var fs = require('fs');
var options = {
  'method': 'GET',
  'url': 'ya.ru',
  'headers': {
  },
  formData: {
    'aa': {
      'value': fs.createReadStream('/C:/Users/Sergei-Pc/Pictures/2019-06-02/002.jpg'),
      'options': {
        'filename': '/C:/Users/Sergei-Pc/Pictures/2019-06-02/002.jpg',
        'contentType': null
      }
    }
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question