在 multer 上传文件之前获取 req.body 个非文件字段

Get req.body of other fields than files before multer uploads the files

我有一个使用 multer 上传文件的功能:

exports.create = (req, res) => {
    console.log("req.body1 : ")
    console.log(req.body)
    var fileFilter = function (req, file, cb) {
        console.log("req.body2: ")
        console.log(req.body)
        // supported image file mimetypes
        var allowedMimes = ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'];

        if (_.includes(allowedMimes, file.mimetype)) {
            // allow supported image files
            cb(null, true);
        } else {
            // throw error for invalid files
            cb(new Error('Invalid file type. Only jpg, png and gif image files are allowed.'));
        }
    };

    let upload = multer({
        storage: multer.diskStorage({
            destination: (req, file, callback) => {
                console.log("req.body3 : ")
                console.log(req.body)
                let userId = req.params.userId;
                let pathToSave = `./public/uploads/${userId}/store`;
                fs.mkdirsSync(pathToSave);
                callback(null, pathToSave);
            },
            filename: (req, file, callback) => {
                callback(null, uuidv1() + path.extname(file.originalname));
            }
        }),
        limits: {
            files: 5, // allow only 1 file per request
            fileSize: 5 * 1024 * 1024, // 5 MB (max file size)
        },
        fileFilter: fileFilter
    }).array('photo');

    upload(req, res, function (err) {
        console.log("req.body4 : ")
        console.log(req.body)
...
...

如您所见,有很多 console.log 通过 POST 方法打印出传入数据的信息。奇怪的是,直到进入上次上传功能后,才出现除文件以外的字段

所以问题是在到达最后一个上传功能之前,我无法使用这些字段验证内容。因此,如果文件以外的其他字段存在任何错误,我将无法取消和删除上传的文件。

以下是上述代码的输出:

req.body : 
{}
req.body2: 
{}
req.body3 : 
{}
req.body4 : 
{ name: '1111111111',
  price: '1212',
  cid: '1',
...

文件上传大约在 console.log("req.body3 : ") 完成。然后它输出 console.log("req.body4 : "). 中的其他字段我需要 req.body4 中出现的其他字段来验证内容上传文件。但我不能,因为这些字段是在文件上传后检索的。

如何在multer真正上传文件之前得到别人的字段?

============================================= ==

附加:

我发现如果我使用 .any() 而不是 .array('photo') 那么我可以同时访问字段和文件。但是,问题仍然是它首先上传这些文件,然后让我可以访问底部 console.log("req.body4 : ") 所在的上传功能中的那些字段。 所以问题仍然是在我需要使用这些字段进行验证之前先上传文件。

您应该只在 body 中接收一个对象 一个 对象,因此您应该能够像访问任何其他对象一样访问它

{
  object1: 'something here',
  object2: {
    nestedObj1: {
      something: 123,
      arrInObj: ['hello', 123, 'cool'],
  }
}

然后你就可以像这样访问这些东西了:

console.log(req.body.object1) // 'something here'
console.log(req.body.object2.nestedObj1[0]) // 'hello'
console.log(req.body.object2.nestedObj1.forEach(item => console.log(item)) // 'hello' 123 'cool'