Upload Image Using AJAX In Node



Introduction
In this blog we see how we can upload image file using ajax.Here we be using FileReader for reading the selected file and then we send that file data to server side using ajax and on server side we read and save that as image on server.


Project Structure



Setup Folder
Open the command prompt and create new folder using following command
  • mkdir upload
Now change to the newly created folder by using folder command
  • cd upload

Setup Node In Folder
Now we have to setup node environment in the folder for our project.
We have to use the below command to setup node in our folder
  • npm init -y
This command will create a package.json file which indicates that node is initialized in folder.
The package.json file will look like this






Install Packages

Now we have to install the package required for building the application.

For installing packages we use npm install followed by package name.


  • npm install body-parser ejs express jquery

After installing package the package.json will look like this 






Add Folder
As you can see in the project structure above. 
Now we have to add a new folder in out project folder and name it views.
And in views folder add file and name it demo.ejs
  • demo.ejs
  • <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    </head>
    <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
    <a class="navbar-brand" href="#">UploadFile</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
    </button>
    </nav>
    <div class="nav justify-content-center">
    <div class="card nav justify-content-center" style="width: 18rem; margin-top:7%;">
    <div class="card-body text-center">
    <input type="file" name="file" id="file" accept="image/*" class="form-control"><br>
    <button type="button" class="btn btn-success" id="upload">uploadfile</button>
    </div>
    </div>
    </div>
    <br>
    <div class="nav justify-content-center img">
    </div>
    <script src="/jquery/jquery.js"></script>
    <script>
    $(document).ready(function(){
    var fileData;
    var myFile;
    $('#file').change(function(){
    var filereader = new FileReader();
    filereader.onload = function(event){
    fileData = event.target.result;
    };
    myFile = $('#file').prop('files')[0];
    console.log('myfile',myFile)
    filereader.readAsDataURL(myFile)
    });
    $('#upload').click(function(){
    $.ajax({
    method:"post",
    url:"/upload",
    dataType:"JSON",
    data:{'filename':myFile.name,'file':fileData},
    success:function(response){
    if(response.msg=="success"){
    alert('uploaded');
    $('#file').val('');
    $('.img').append('<img src="data:image/*;base64,'+response.data+'" style="width:300px;height:300px;margin:10px 10px 10px 10px;">')
    }
    },
    error:function(){
    alert('server error');
    }
    });
    });
    });
    </script>
    </body>
    </html>
    view raw demo.ejs hosted with ❤ by GitHub
Setup EntryPoint
We have to setup the entry point for our application.
Add a new file in our project folder and name it app.js.As show in the project folder
Now add the below code in that app.js
  • app.js
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express();
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended:true,limit:'50mb',parameterLimit:50000}));
app.use('/jquery',express.static(__dirname+'/node_modules/jquery/dist/'));
app.get('/',(req,res)=>{
res.render('demo');
});
app.post('/upload',(req,res)=>{
var path = __dirname+'/'+req.body.filename;
var image = req.body.file;
var data = image.split(',')[1];
fs.writeFileSync(path,data,{encoding:'base64'});
var temp = fs.readFileSync(path);
var buff = new Buffer(temp);
var base64data = buff.toString('base64');
res.json({msg:'success',data:base64data});
});
var port = process.env.port || 3000;
app.listen(port,()=>console.log('server run at port '+port));
view raw app.js hosted with ❤ by GitHub

Now open the pacakge.json file and in scripts add "start":"node app.js"
and in main change it to app.js from index.js.

Download code from here

Watch Video Tutorial 

Comments

Popular posts from this blog

How To Use Sequelize-Cli In Node

Upload And Download File In Node

Import CSV File Data Into MongoDB In Node