使用node.js接收POST请求

时间:2013-07-21 13:10:12

标签: javascript node.js http ip-camera

我有一台安讯士M1011相机,它设置为只要检测到动作就会向服务发送一系列jpeg图像(使用HTTP POST)。我正在使用node.js构建服务。

我已经成功接收带有标题的POST请求,但是我无法在请求正文中保存数据。这是代码:

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();
            }
        });

    });

}

在控制台上,我得到了这种输出。当然,内容长度因文件而异:

{ 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

问题是我在tmp文件夹中得到一个相同的,已损坏的文件,大小约为33KB,无论图像有多大。接收这些文件我做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要处理POST请求以获取已发送的文件。在POST请求中提交文件时,您将文件元数据和数据包装起来并发送到服务器。

服务器必须解码请求,并获取文件。仅仅保存请求是行不通的。您没有提到是否使用任何Web服务器框架。你最好使用像express这样的人为你做这件事。 Express将解析请求,获取文件对象并将文件保存到临时文件中。