Search code examples
node.jsmulter

display file name in a single array in multer using nodejs


here is a part of my code of multer using nodejs

const storageEngine = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './Images')
        const Files = [file.originalname]
        console.log(Files)
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
})

the console log of the above code is this:

['image.png']
['image2.png']
['image3.png]

so i want all file names to be in one array to be posted in mysql in one go as i do not want to send multiple request to mysql as there are numerous amount of images.

so all i want is the file names to be present in one single array like this:

['image.png', 'image2.png', 'image3.png']

Solution

  • The destination event that you use is invoked once per uploaded file, so you cannot use it to collect all file names.

    Assuming you have an input field <input type="file" multiple name="upload">, you can instead use

    app.use(storageEngine.array("upload"))
    .use(function(req, res, next) {
      console.log(req.files.map(file => file.originalname));
      next();
    });