node.js 如何使用 ExpressJS 4 上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23340548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:13:57  来源:igfitidea点击:

How to upload files use ExpressJS 4?

node.jsexpress

提问by vcLwei

From ExpressJS 4 API, I find the req.files was invalid. How to upload files use ExpressJS 4 now?

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

采纳答案by Vinz243

express.bodyParseris not included in express 4 by default. You must install separately. See https://github.com/expressjs/body-parser

express.bodyParser默认情况下不包含在 express 4 中。您必须单独安装。见https://github.com/expressjs/body-parser

Example :

例子 :

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

var app = connect();

app.use(bodyParser());

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

There is also 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;

Here is how I did it:

这是我如何做到的:

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!
      // ...
    });
  });
});

回答by MikeSmithDev

I just had this issue after upgrading, where req.fileswas undefined. I fixed it by using multer.

升级后我刚刚遇到了这个问题,哪里req.files是未定义的。我使用multer修复了它。

So,

所以,

npm install multer

and then in your app.js

然后在你的 app.js

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

I didn't have to change anything else after that and all my old functionality worked.

在那之后我不必更改任何其他内容,我所有的旧功能都可以使用。