This question already has answers here:
File uploading with Express 4.0: req.files undefined

(9个答案)


5年前关闭。




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

最佳答案

默认情况下,Express 4中不包括express.bodyParser。您必须单独安装。参见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!
      // ...
    });
  });
});

10-08 04:40