在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,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,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字段。 所以问题仍然在于,在我需要使用这些字段进行验证之前,首先要上传文件。

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

您应该仅在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'
本文链接:https://www.f2er.com/3107749.html

大家都在问