Upload Image with Nodejs and Express

Hello World, Today we are going to discuss how to upload image with nodejs and express. Before reading this article I request to you read the following tutorial so that you can the basic knowledge about nodejs web development.

I have divided this tutorial in following parts:

  • Set up Projects.
  • Create Views.
  • Upload Image in folder and view the image.

Set up Project

  • Open command prompt and go the folder where you want to create the project.
  • Make uploadImage Directory and go to this directory.
  • Initiate the following command.

npm init

Skip the step with enter button.

Now run the following command for installing the dependencies:

npm install express jade body-parser multer --save

You can read about the above packages on npm website.

  • Create index.js file with the following code.
var express=require('express');
var bodyParser=require('body-parser');
// For Image
var multer  = require('multer');
var upload = multer({dest: '/public/uploads/'})
var fs=require('fs');
var path=require('path');

var app=express();

// Images View Start

// Show Image
app.get('/show-image/:img_url',function(req,res){
    res.render('image',{'imgUrl':req.params.img_url});
});

// Show Image Form
app.get('/',function(req,res){
    res.render('add-image');
});

// Images View Start
// Add Image
app.post('/add-image',upload.single('image'),function(req,res){
    // Save Image
    var possible='abcdefghijklmnopqrstuvwxyz123456789';
    var imgUrl='';
    for(var i=0; i<6; i++){
        imgUrl+=possible.charAt(Math.floor(Math.random()*possible.length));
    }
    var tempPath=req.file.path;
    var ext=path.extname(req.file.originalname).toLowerCase();
  //   Create Upload Folder in Public Folder
    var targetPath=path.resolve('./public/uploads/'+imgUrl+ext);
    if(ext==='.png' || ext==='.jpg' || ext==='.jpeg' || ext==='.gif'){
      fs.rename(tempPath,targetPath,function(err){
          if(err) throw err;
          res.redirect('/show-image/'+imgUrl+ext);
      });
    }else{
        fs.unlink(tempPath,function(){
            if(err) throw err;
            res.json(500,{error:'Only image files are allowed'});
        });
    }
  // Save Image End
});
// Images View End

// Set the view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// Set Public Folder as static Path
app.use(express.static(path.join(__dirname, 'public')));

// Run the Server
app.listen('3000',function(){
    console.log('Server is running at PORT '+3000);
});

In the above file we have checked the valid image extension. After successful image upload we have redirected on image path so that we can see the uploaded image. You can also check uploads directory in public folder.

Create Views

  • Create public folder at root and uploads folder in public folder.
  • Create the views folder on root with following two files.
//- add-image.jade
html
    head
        title Add Image
        link(rel="stylesheet",href="/stylesheets/style.css",type="text/css")
    body
        div.container
            div.top-menu
                h1.page-heading Add Image
                ul
                    li
                        a(href='/add-image') Add Image
            div.page-content
                p.page-description We are adding image
                hr
                //- Change in Form Type
                form(action='/add-image',method='post',enctype="multipart/form-data")
                    table(cellpadding="10",cellspacing="10")
                        //- Add Image File Start
                        tr
                            td
                                label(for="file") Select Image
                            td
                                input(type="file",name="image")
                        //- Image File End
                        tr
                            td(colspan="2",align="right")
                                input(type="submit")
                            

 

//- Show Image.jade
html
    head
        title Show Image
        link(rel="stylesheet",href="/stylesheets/style.css",type="text/css")
    body
        div.container
            div.top-menu
                h1.page-heading Image
                ul
                    li
                        a(href='/') Add Image
            div.page-content
                p.page-description Show Image
                p.image-show
                    img(src='/uploads/'+imgUrl)
  • Create stylesheets folder in public folder with style.css file  folder with following code.
body{
    font-family:Arial, Helvetica, sans-serif;
}
h1,ul{
    margin: 0px;
    padding: 0px;
}
.container{
    width:1000px;
    margin: 0 auto;
    height: auto;
    padding:10px;
    border:1px solid #ccc;
    box-shadow:0px 0px 5px #ccc;
    margin-top:5%;
    overflow: auto;
}
.top-menu{
    border-bottom:1px solid #ddd;
    padding-bottom:5px;
    overflow: auto;
    margin-bottom: 30px;
}
.page-heading{
    float: left;
}
.top-menu ul{
    float: right;
}
.top-menu ul li{
    list-style: none;
    display: inline-block;
}
.top-menu ul li a{
    display: block;
    padding: 10px 5px;
    text-decoration: none;
    font-size: 13px;

}

/* Button STyling */
.button{
    padding:5px;
    font-size: 13px;
    background: #ccc;
    margin: 5px;
    color: blue;
}

Create Views

  • Run your server and you will see the following screenshot.

upload-image

show-uploaded-image

Leave a Reply

Your email address will not be published. Required fields are marked *