使用 multer 重命名文件

Renaming files using multer

我已将 multer 配置为;

var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null,  '../images/profile');
  },
  filename: function(req, file, cb) {
    cb(null, req.body.username + '.jpeg');  // file does not get renamed
  }
});

var upload = multer({storage: storage});

// Route that uses multer
router.post('/auth/signup/upload', upload.single('image'), function(req, res) {
  console.log(req.body.username); // contains value
  res.send(); 
});

虽然 req.body.username 有一个值,但文件没有重命名。 我在这里错过了什么?

来自 multer 手册:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

遗憾的是,我认为没有解决此问题的好方法。您可以尝试切换 HTML 表单中字段的顺序,但这可能不会导致跨浏览器的行为一致。您也可以改为在查询字符串中发送用户名(即 POST 文件到 http://foo.bar?username=me)。您也可以之后手动移动文件,或者将用户名和文件之间的映射存储在其他地方。