如何使用ExpressJS 4上传文件?

时间:2014-04-28 11:59:06

标签: node.js express

ExpressJS 4 API,我发现req.files无效。 如何上传文件现在使用ExpressJS 4?

2 个答案:

答案 0 :(得分:23)

升级后我刚遇到此问题,其中req.files未定义。我使用multer修复了它。

所以,

npm install multer

然后在你的app.js

var multer = require('multer');
app.use(multer({ dest: './tmp/'}));

之后我没有必要改变任何其他内容,而且所有旧功能都有效。

答案 1 :(得分:3)

默认情况下,

express.bodyParser未包含在快递4中。您必须单独安装。见https://github.com/expressjs/body-parser

示例:

var bodyParser = require('body-parser');

var app = connect();

app.use(bodyParser());

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next();
})

还有node-formidable

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(util.inspect({fields: fields, files: files}));
});

return;

我是这样做的:

form = new formidable.IncomingForm();
form.uploadDir = __dirname.getParent() + "/temp/";
form.parse(req, function(err, fields, files) {
  var newfile, path, uid, versionName;
  uid = uuid.v4();
  newfile = __dirname.getParent() + "/uploads/" + uid;
  copyFile(files.file.path, newfile, function(err) {
    if (err) {
      console.log(err);
      req.flash("error", "Oops, something went wrong! (reason: copy)");
      return res.redirect(req.url);
    }
    fs.unlink(files.file.path, function(err) {
      if (err) {
        req.flash("error", "Oops, something went wrong! (reason: deletion)");
        return res.redirect(req.url);
      }
      // done!
      // ...
    });
  });
});