Nodejs POST request multipart/form-data


I am trying to upload a photo via a POST request with the request module

According to the readme I should just be able to do this

var r ="", requestCallback)
var form = r.form()
form.append("folder_id", "0");
form.append("filename", fs.createReadStream(path.join(__dirname, "image.png")));

function requestCallback(err, res, body) {

The problem is, this doesn't work. I get a reply from the test server saying it dumped 0 post variables.

I have confirmed that the server is in working condition with this little html page

        <form action="" method="post" enctype="multipart/form-data">
            File: <input type="file" name="submitted">
            <input type="hidden" name="someParam" value="someValue"/>
            <input type="submit" value="send">

So the question is, what am I doing wrong with the request module? Is there a better way to send multipart/form-data with node?

12/10/2012 2:05:31 PM

Accepted Answer

After some more research, I decided to use the restler module. It makes the multipart upload really easy.

fs.stat("image.jpg", function(err, stats) {"", {
        multipart: true,
        data: {
            "folder_id": "0",
            "filename": restler.file("image.jpg", null, stats.size, null, "image/jpg")
    }).on("complete", function(data) {
12/11/2012 1:11:29 PM

So I just got done wrestling with this myself and here is what I learned:

It turns out that neither request or form-data are setting the content-length header for the generated body stream.

Here is the reported issue:

The solution posted by @lildemon gets around this by:

  1. Generating the FormData object
  2. Getting it's length
  3. Making the request and setting the form object and content-length header explicitly

Here is a modified version of your example:

var request = require('request');
var FormData = require('form-data');

var form = new FormData();
form.append("folder_id", "0");
form.append("filename", fs.createReadStream(path.join(__dirname, "image.png")));

form.getLength(function(err, length){
  if (err) {
    return requestCallback(err);

  var r ="", requestCallback);
  r._form = form;     
  r.setHeader('content-length', length);


function requestCallback(err, res, body) {

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow