node.js使用PUT上传

时间:2011-04-10 10:21:37

标签: node.js

我看过(很少)在node.js中上传服务器的例子, 使用multipart或强大的lib,处理http post。

但是,如果我想使用PUT上传文件,那就像

%curl -T file.tar.gz http://node:8000/upload/

你能指点我一些例子吗? 我如何阅读请求正文?

招呼

1 个答案:

答案 0 :(得分:1)

也许我错了,但如果你采取强大的例子,将'post'替换为'put'应该有效。

var formidable = require('formidable'),
    http = require('http'),
    sys = require('sys');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'put') {
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(sys.inspect({fields: fields, files: files}));
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
});