DEV Community

Cover image for Multiple fields File upload with Multer in Nodejs Express application
Street_Coder
Street_Coder

Posted on

Multiple fields File upload with Multer in Nodejs Express application

Multer is a node. js middleware for handling multipart/form-data , which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

npm install multer

After Installation you need to require the multer package in your application

const multer = require('multer')

to use multer in your nodejs app

To setup multer as middleware function in this app were mainly focusing on multer for Image file upload you can handle whatever file you want

const multer = require('multer');

const storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, 'Uploads');
    },
    filename: function(req, file, cb){
        cb(null, new Date().toISOString() + '' + file.originalname)
    },
    fileFilter: function(req, file, cb){
        if(file.minetype === 'image/png' || file.minetype === 'image/jpg' || file.minetype === 'image/peg'){
            cb(null, true)
        }else{
            cb(null, false, "Invalid File format Upload Image")
        }
const multer = require('multer');

const storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, 'Uploads');
    },
    filename: function(req, file, cb){
        cb(null, new Date().toISOString() + '' + file.originalname)
    },
    fileFilter: function(req, file, cb){
        if(file.minetype === 'image/png' || file.minetype === 'image/jpg' || file.minetype === 'image/peg'){
            cb(null, true)
        }else{
            cb(null, false, "Invalid File format Upload Image")
        }
    }
})
}
})

Enter fullscreen mode Exit fullscreen mode

After decide the file type we want to handle and filesize

let create our FileUpload function and past some parameters to it

const Fileuploads = multer({
    storage: storage,
    limits: {
       fileSize: 1024 * 1024 * 5 
    }

}).fields([{name: 'fimgsrc'}, {name: 'bimgsrc'}, {name: 'logosrc'}])


module.exports = Fileuploads;

Enter fullscreen mode Exit fullscreen mode

As we exported our FileUpload middleware

We can simply use it in our routes to handle fileUploads to our Nodejs Express Server in side our App.js file

const FileUpload = require('./middleware/FileUpload');

app.post('/createMenu', FileUpload, postMenuController);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)