Receiving POST request with node.js

I have an Axis M1011 camera which is set up to send a series of jpeg images as long as it is detecting motion, to a service (using HTTP POST). I'm building the service using node.js.

I'm successfully receiving POST requests with their headers, but I am having trouble saving the data in the body of the request. Here is the code:

function addEvent(req, res)
{
    var buffer = '';
    console.log(req.headers);
    req.on("data", function(chunk)
    {
        console.log("chunk received");
        buffer += chunk;
    });
    req.on("end", function()
    {
        console.log("saving file");
        fs.writeFile("./tmp/"+ new Date().getTime()+".jpg", buffer, function(error)
        {
            if(error)
            {
                console.log(error);
            }
            else
            {
                console.log("saved");
                res.send("OK"); 
                res.end();
            }
        });

    });

}

On the console, I get this kind of output. Ofcourse, the content-length differs from file to file:

{ host: '192.168.0.100:8888',
  'content-type': 'image/jpeg',
  'content-disposition': 'attachment; filename="file13-07-19_20-49-44-91"',
  'content-length': '18978' }
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
chunk received
saving file
saved

The problem is that I am getting one same, corrupted, file in the tmp folder which size is about 33KB, no matter how big is the image. What am I doing wrong with receiving these files?

You need to process the POST request to get the file that has been sent. When you submit a file in POST request, you wrap file meta data as well as data and send it to the server.

The server has to decode the request, and get the file. Simply saving the request won't do. You did not mention if you are using any web-server framework. It is better you use one like express which does this for you. Express will parse the request, get the file object and save the file into temporary file.