for uploading images that could be of any name or any quantity.
Currently I am handling file upload with multer in my project. I can handle multiple file upload when i know field name. I am storing the path of each file in MongoDB, and mongoose.Below I shared the knowledge with know field-name like, image & images
in router:
uploadImages.fields([
{ name: 'image', maxCount: 1 },
{ name: 'images', maxCount: 8 }
])
now the problem is I have RANDOM FILE and I dont know all the field name . like there can be 10 filed and each field can have multiple file, like banner, slider, logo, image, cover and so on. How do I handle this case? When i don't know the fields name and number of images in each fields
So The answer was pretty easy. I was using mutter. muter has any() field.
any(): Accepts all files that comes over the wire. An array of files will be stored in req.files
It handles all the files coming, with any field name:
const fileUpload = multer({
storage: multer.diskStorage ({
destination: (req, file, cb)=>{
cb(null, 'uploads/slider')
},
filename : (req, file, cb) =>{
cb(null, file.filename)
}
})
})
module.exports = fileUpload
Now in router:
const upload = require('../middleware/slider')
router.post('/', upload.any(), ......)
upload.any()
get all files in controller to store the path in database
exports.controller = async (req, res, next)=>{
const files = req.files
console.log(files)
// files will contain an array of file, all the file you uploaded.
//to get the path of each
let sliders = []
if(files){
sliders = files.map(file=>{
return {field_name:file.fieldname , path :file.path }
})
}
console.log(sliders)
}
So that how i solved the answer. any() filed saved my day.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.