如何处理NodeJS中的文件上传?

时间:2012-06-09 02:11:21

标签: node.js file-upload request

我有这段代码:

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 file=@filetoupload.txt这样的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--

现在的问题是,有没有什么好方法可以捕获文件名的值和文件的内容?或者我是否必须使用某种正则表达式voodoo来提取上述内容的值?

我想在没有像express这样的第三方模块的情况下这样做,首先是因为我想了解它是如何工作的,其次是因为快速'bodyParser()将所有文件保存到磁盘然后其他模块如强大的必须从磁盘读取,我正在尝试制作能够将文件直接上传到Rackspace CloudFiles而无需先保存到磁盘的东西。

2 个答案:

答案 0 :(得分:1)

阅读Formidable中的代码(Connect,以及Express,用于处理文件上传)并将其用作起点,修改您不喜欢的行为(例如保存到磁盘)。

答案 1 :(得分:1)