在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("照片"(,那么我可以访问字段和文件。但问题仍然是,它先上传这些文件,然后让我访问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'

最新更新