2

In NodeJS I am trying to POST JSON data to the server along with a file using the following code:

unirest.post(url)
.headers(headers)
.send(data)
.attach('file', file)
.end(function (response) {
    var statusCode = response.status;
    if (statusCode != 200) {
        console.log("Result: ", response.error);
    }
});

However, on the server, I am only receiving the file, and not the JSON object from .send(data). I see there is a .multipart() function I can use, but I'm not sure how best to use this?

ralfe
  • 1,412
  • 2
  • 15
  • 25

1 Answers1

3

When you send JSON data over http, content type is application/json. when you send files over http, content type is multipart/form-data. You can send form fields while sending a multipart request but you can't send JSON data in multipart request. You have 2 options to send this request

  1. While using multipart/form-data, Stringify you JSON data and send it as a form field and parse it on other end
  2. While using application/json, Base64 you file and send it as a property in your JSON data
Gurbakhshish Singh
  • 1,034
  • 1
  • 10
  • 25