Reputation: 1415
What I am building allows user's to create groups and within each group hold files. I have this set up but am having trouble looping through the files within the group on my server side (express js).
Before I send to my server I build my formData like this
// loop through groups
for(var i = 0; i < data.groups.length; i++) {
formData.append('groups[]', data.groups[i])
// loop through photos in group
for(var s = 0; s < data.groups[i].length; s++) {
formData.append('photos[]', data.groups[i][s])
}
}
Now on my server side groups can be looped through. However with Multer as my middleware my photos aren't being received in arrays. My files come in as objects within one array in req.files. So instead of having groups[0]/req.files[0] with 2 files and groups[1]/req.files[1] with 1 file. I have groups[0] with 2 files and req.files[0] with 3 files making it difficult to match the groups with their respected photos.
Any idea how I can get my req.files to hold array's instead of every file in an object such as...
[
[ { file }, { file } ],
[ { file } ]
]
// rather than
[
{
file
},
{
file
},
{
file
}
]
** am leaning towards upload.fields() in attempts at a solution but haven't worked it out yet
Upvotes: 0
Views: 317
Reputation: 29172
You need to add the group index to the field name:
// loop through groups
for(var i = 0; i < data.groups.length; i++) {
// loop through photos in group
for(var s = 0; s < data.groups[i].length; s++) {
var fieldname = 'photos[' + i + '][]';
formData.append(fieldname, data.groups[i][s])
}
}
But the problem is that the multer does not process the nested arrays (PHP's naming conventions). So pay attention to other middleware, for example on express-form-data
.
Upvotes: 1