2012-06-09 19 views
0

我有這樣的代碼:如何處理NodeJS中的文件上傳?

http.createServer(function (req, res) { 
    if (req.method.toLowerCase() === "post") { 
    res.writeHead(200); 
    req.on('data', function (data) { 
     console.log(data.toString()); 
    }); 
    res.end(); 
    } 
}).listen(8006); 

,如果我嘗試上傳文件像curl http://localhost:8006/upload -X POST -F [email protected]一個curl命令,我會得到的文件名和文件打印出來的內容,在這個情況如下:

------------------------------5d02ba973600 
Content-Disposition: form-data; name="file"; filename="filetoupload.txt" 
Content-Type: text/plain 


<!-- start slipsum code --> 

Do you see any Teletubbies in here? Do you see a slender 
plastic tag clipped to my shirt with my name printed on 
it? Do you see a little Asian child with a blank expression 
on his face sitting outside on a mechanical helicopter that 
shakes when you put quarters in it? No? Well, that's what 
you see at a toy store. And you must think you're in a 
toy store, because you're here shopping for an infant 
named Jeb. 

<!-- end slipsum code --> 


------------------------------5d02ba973600-- 

現在的問題是,有沒有什麼好方法來捕獲文件名的值和文件的內容?或者我將不得不進入某種正則表達式巫術來提取上述內容的值?

我想這樣做沒有任何第三方模塊像快遞,首先,因爲我想了解它是如何工作的,其次,因爲express'bodyParser()將所有文件保存到磁盤,然後像強大的其他模塊從磁盤讀取數據,我正在嘗試將文件直接上傳到Rackspace CloudFiles,而不必先保存到磁盤。

回答

1

通讀Formidable中的代碼(哪個Connect,因此Express用於處理文件上傳)並將其用作起點,修改您不喜歡的行爲(如保存到磁盤)。

+0

這是一個巨大的代碼庫,我想我會需要很長的時間去了解它......但是,直到沒有人回答它的最好我可以做... –

+0

你認爲這可能表明處理表單上傳本質上是一個相當困難的過程,需要能夠處理一大堆特殊情況和錯誤條件?我做。很容易陷入「我可以做得更好更簡單」的陷阱。有時候做這些的人是對的。更多的時候他們錯了。 – ebohlman