在multer上传文件之前,获取文件以外的其他字段的req.body

来了

我有一个使用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:”)底部的uploads函数中的that字段。因此,问题仍然在于,在我需要使用这些字段进行验证之前,首先要上传文件。

法国

您应该在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'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章