Multer Single File Upload with Express and Node JS

By Digamber Rawat Last updated on
In this tutorial, we are going to create a single file uploading system using Multer, Express.js, and Node.js. This tutorial is best suitable for beginners who are just getting started. To know more about Multer middleware methods, read the official documentation here.

Multer is a middleware for handling multipart/form-data, extremely useful for managing file uploads. We will use Express.js middleware framework to build the single file upload system along with Multer and Node.js.

Set up Node App for Single File Uploading Tutorial

Run command and hit enter to create app folder:

mkdir multer-file-upload && cd multer-file-upload

Generate exclusive package.json file

npm init

Install required NPM packages:

npm install multer express cors body-parser

Create app.js to store server settings for Multer file uploading system:

touch app.js

Once all these packages installed, these are registered inside the package.json file:

{
  "name": "multer-single-file-upload",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Digamber Rawat",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "multer": "^1.4.2"
  }
}

Multer Single File Upload Tutorial

In the main app.js file, we will import the following NPM packages: express, path, cors, multer and bodyParser.

const express = require('express');
const path = require('path');
const cors = require('cors');
const multer = require('multer');
const bodyParser = require('body-parser');
Package Detail
Express It’s a robust Node.js web application framework that helps in creating powerful REST APIs.
PATH The path module helps in working with directory and file paths in node apps.
CORS It’s a node.js package helps in enabling Access-Control-Allow-Origin CORS header.
Multer It’s a node.js middleware plugin helps in managing the multipart/form-data and file uploads.
bodyParser This package extracts the entire body portion of an incoming request stream and exposes it on req.body.

Run below command to create public folder in the root of the project directory, here we will store the uploaded files:

mkdir public

Define `public` folder path in app.js file.

const PATH = './public/';

Define multer.diskStorage({ }) method and pass destination and filename middleware functions inside of it as mentioned below.

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR);
  },
  filename: (req, file, cb) => {
    const fileName = file.originalname.toLowerCase().split(' ').join('-');
    cb(null, fileName)
  }
});

Then, we will validate file types such as: .jpeg, .jpg, .png and .gif in Multer single file upload system using fileFilter and file.mimetype options.

const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == "image/gif") {
cb(null, true);
} else {
cb(null, false);
return cb(new Error('Allowed only .png, .jpg, .jpeg and .gif'));
}
}
});

This method will validate files during file upload in node.js app if the file type is relevant then it will store the file in `public` folder else throw the error.

Final output:

const express = require('express');
const path = require('path');
const cors = require('cors');
const multer = require('multer');
const bodyParser = require('body-parser');
const PATH = './public/';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
const fileName = file.originalname.toLowerCase().split(' ').join('-');
cb(null, fileName)
}
});
const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == "image/gif") {
cb(null, true);
} else {
cb(null, false);
return cb(new Error('Allowed only .png, .jpg, .jpeg and .gif'));
}
}
});
app.post('/add', upload.single('image'), (req, res, next) => {
const user = new User({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
imageURL: req.file.path
});
user.save().then(result => {
res.status(201).json({
message: "User registered successfully!",
})
})
})
app.listen(3000, function () {
console.log("Working on port 4000");
});

Conclusion

Finally, we have completed the single file upload tutorial using Multer/Express and Node.js. I hope you loved this tutorial, please consider it sharing with others.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me