How to upload a file using POST request in Node.js?

Sometimes, we want to upload a file using POST request in Node.js.

In this article, we’ll look at how to upload a file using POST request in Node.js.

How to upload a file using POST request in Node.js?

To upload a file using POST request in Node.js, we can submit our files in a form data object.

For instance, we write

const req = request.post(url, (err, resp, body) => {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});

const form = req.form();
form.append('file', '<FILE_DATA>', {
  filename: 'myfile.txt',
  contentType: 'text/plain'
});

to call request.post with to make a POST request object req.

Then we call req.form to create a form form data object.

Then we call form.append with the name of the file input, the file data, and the file metadata respectively.

We get the response from body in the request.post callback.

Conclusion

To upload a file using POST request in Node.js, we can submit our files in a form data object.