2013-07-21 80 views
1

我有一個Axis M1011相機,它設置爲只要檢測到運動,就會向服務(使用HTTP POST)發送一系列jpeg圖像。我正在使用node.js構建服務。使用node.js接收POST請求

我成功地接收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(); 
      } 
     }); 

    }); 

} 

在控制檯上,我得到了這種輸出。 Ofcourse,內容長度從文件的不同而不同文件:

{ 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 

的問題是,我得到一個相同的,損壞的,其中大小約爲33KB,不管有多大的圖像tmp文件夾的文件。我在接收這些文件時做錯了什麼?

+0

你知道如何解決這個問題嗎? – bubakazouba

+0

說實話,沒有。我之後使用過node.js,我想我實際上已經開始工作,但在這種情況下,我不知道哪裏出了什麼問題。也許現有的答案有意義,但我沒有解決。 –

回答

0

您需要處理POST請求以獲取已發送的文件。當您在POST請求中提交文件時,您將文件元數據以及數據封裝並將其發送到服務器。

服務器必須對請求進行解碼並獲取文件。只保存請求不會。您沒有提及您是否使用任何Web服務器框架。你最好使用一個像express這樣爲你做的。 Express將解析請求,獲取文件對象並將文件保存到臨時文件中。

+0

是的,我使用快遞。我也嘗試使用express body parser,但沒有運氣,因爲服務器在打開後停止響應。這可能是我錯用了它。這應該如何用快遞完成? –

+0

其實我必須糾正自己,req.body是空的,儘管使用了bodyParser。 –