使用Connect + formidable在Nodejs中上传文件

时间:2014-11-14 05:35:39

标签: node.js file-upload connect formidable

我无法使用Connect框架上传文件。我已经提到了链接Connect 。以下是我的代码

app.use(connectDomain())
    .use(connectRoute(function (router) {
        router.post('/upload', function (req, res) {
            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(JSON.stringify({fields: fields, files: files}));
            });

我总是得到如下的回复

received upload:

{"fields":{},"files":{}}

1 个答案:

答案 0 :(得分:0)

在强大的模块中给出的例子..

    var files = [],
    fields = [];
form
  .on('field', function(field, value) {
    console.log(field, value);
    fields.push([field, value]);
  })
  .on('file', function(field, file) {
    console.log(field, file);
    files.push([field, file]);
  })
  .on('end', function() {
    console.log('-> upload done');
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received fields:\n\n '+util.inspect(fields));
    res.write('\n\n');
    res.end('received files:\n\n '+util.inspect(files));
  });
form.parse(req);