Image Upload Using NodeJS & Multer

Image Upload Using NodeJS & Multer

Here we are doing upload image using multer and nodejs. So, let's get start.

Let's start with creating a package.json file

npm init

now we create a server file to execute our code.

touch server.js

Now We go with express js.

In this Small Image Upload Task, We need express js for creating routes.

const express = require('express');

const app = express();

then multer npm is used for file upload so in this task we use multer for image upload.

const multer = require('multer');

now we go for ejs.

What is ejs?

ejs is template engine and it's use for create a template and we can put that content dynamically.

const ejs = require('ejs');

app.set('view engine', 'ejs');

now let's start the server and create one api of get route

const port = 3002;

app.listen(port, () => console.log(`Server started on port ${port}`));

now create one API for GET route.

app.get('/', (req, res) => res.send('hello world'));

now your server file is like this.

server.js

const express = require('express');
const multer = require('multer');
const ejs = require('ejs');

// [ Init app ]
const app = express();

// [ EJS ]
app.set('view engine', 'ejs');

app.get('/', (req, res) => res.send('hello world'));

const port = 3002;
app.listen(port, () => console.log(`Server started on port ${port}`));

Now we are set render to ejs.

create a folder "views" and inside view folder create index.ejs file.

index.ejs

now Set The multer storage engine

// Set The Storage Engine
const storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, cb){
    cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

Here, destination is your folder path, you need to uplaod your image in folder & filename is you can set your image name as per your requirement

Now we go for uplaod in multer flow

const upload = multer({
  storage: storage,
  limits:{fileSize: 1000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
}).single('myImage');

Here, we can set the image uplaod limit and also checking the file. if you want to uplaod one image then .single function is use and inside .single function pass the value which is you are set in your html page or ejs page.

now this function is for image file checking,

function checkFileType(file, cb){
  // Allowed ext
  const filetypes = /jpeg|jpg|png|gif/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

now we set the public folder for image

// Public Folder
app.use(express.static('./public'));

now let's write uplaod api's code.

app.post('/upload', (req, res) => {
  upload(req, res, (err) => {
    if(err){
      res.render('index', { msg: err });
    } 
    else {
      if(req.file == undefined){
        res.render('index', { msg: 'Error: No File Selected!' });
      } else {
        res.render('index', { msg: 'File Uploaded!', file: `uploads/${req.file.filename}` });
      }
    }
  });
});

Here we create post method api for image upload.

Now your server.js file this

const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const path = require('path');

// Set The Storage Engine
const storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function(req, file, cb){
    cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

// Init Upload
const upload = multer({
  storage: storage,
  limits:{fileSize: 1000000},
  fileFilter: function(req, file, cb){
    checkFileType(file, cb);
  }
}).single('myImage');

// Check File Type
function checkFileType(file, cb){
  // Allowed ext
  const filetypes = /jpeg|jpg|png|gif/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

// Init app
const app = express();

// EJS
app.set('view engine', 'ejs');

// Public Folder
app.use(express.static('./public'));

app.get('/', (req, res) => res.render('index'));

app.post('/upload', (req, res) => {

  upload(req, res, (err) => {

    if(err){
      res.render('index', {
        msg: err
      });
    } else {
      if(req.file == undefined){
        res.render('index', {
          msg: 'Error: No File Selected!'
        });
      } else {
        res.render('index', {
          msg: 'File Uploaded!',
          file: `uploads/${req.file.filename}`
        });
      }
    }
  });
});

const port = 3002;

app.listen(port, () => console.log(`Server started on port ${port}`));

Now start your server with using this command.

npm start

after starting your node server open browser and type localhost with portnumber like this,

localhost:3002

you see this page

screenshot-localhost_3002-2021.10.22-23_05_53.png

Now upload the image and check in your public > uploads folder.

Full code is in my git repository so please check it. Github Repository: darshanraval7 - NodeJS-Image-Upload-Using-Multer-Jquery

Thank you so much :)