File upload in node js is one hell of a job. Not knowing how is makes it a bit more troublesome. File upload is used at a number of places like image upload, excels for bulk upload etc.

Install Multer

npm install --save multer

from here you can get more details about multer.

Configuring Multer

The preferable place to add the multer configuration is in the routes file.

const multer = require("multer")

const upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, "Uploads")
        },
        filename: (req, file, cb) => {
            cb(
                null,
                file.fieldname + "-" + Date.now() + "-" + file.originalname
            )
        }
    }),
    fileFilter: (req, file, cb) => {
        if (
            file.mimetype ===
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        ) {
            cb(null, true)
        } else {
            cb(null, false)
            return cb(new Error("Only .xlsx format allowed!"))
        }
    }
})

Adding Multer to Route

app.post("/api/file-upload/v1", upload.single("file-key"), (req, res) => {
        console.log(req.file)
        res.send("File uploaded successfully!")
    })

Assuming

<form action="/api/file-upload/v1" method="post" enctype="multipart/form-data">
  <input type="file" name="file-key" />
</form>

Validations

all the validation are to be put in fileFilter section as per the requirement. For this case the system only allow excels to be uploaded.

and we are done.

Feel free to comment you suggestions.