Thursday, 5 May 2022

Upload File in Node JS Express using Multer

File Upload in Node js Express using Multer


File Upload is a very common feature in the any type of web based application. This is Node.js tutorial with Express web framework and with Node.js and Express framework we will use Multer Library for implement file upload operation in your application with very easy step. Under this tutorial, we will learn you how to upload files on the server by using Multer and Express framework under Node.js. The main goal of this tutorial is that you can easily developed application in which we can easily handle file upload feature. With the help of this tutorial you will be able to add the file upload in your Node.js web based application using Express framework and Multer Library.

Follow Following Steps for Upload File in Node JS Express using Multer.

  1. Create Node JS Application Directory
  2. Install Express Generator
  3. Install Express Application
  4. Install Dependencies
  5. Install Multer Library
  6. Create Route for Load File Upload Form
  7. Set New Route file Rule in app.js
  8. Create File Upload File
  9. Handle File Upload Request
  10. Display Uploaded File

Step 1 - Create Node JS Application Directory


Firstly, we have to create new directory for Node application. So go into command prompt and go into directory, where you want to create node application directory, and after this you have to run following command.


mkdir file-upload


This command will create file-upload directory. Next we want to go into this directory, so we have to run following command. So after run this command we will go into this directory.


cd file-upload





Step 2 - Install Express Generator


After going into directory in which we want to create node js file upload application. And after this, we have want to install Express generator, so for this, we have to run following command.


npm install -g express-generator


Step 3 - Install Express Application


Next we want to install Express Application, So we have to run following command which will install express application.


npx express --view=ejs


Under this command ejs is a template engine of Express framework. So after run following command you will get following instruction.


   create : nodeapp\
   create : nodeapp\public\
   create : nodeapp\public\javascripts\
   create : nodeapp\public\images\
   create : nodeapp\public\stylesheets\
   create : nodeapp\public\stylesheets\style.css
   create : nodeapp\routes\
   create : nodeapp\routes\index.js
   create : nodeapp\routes\users.js
   create : nodeapp\views\
   create : nodeapp\views\error.ejs
   create : nodeapp\views\index.ejs
   create : nodeapp\app.js
   create : nodeapp\package.json
   create : nodeapp\bin\
   create : nodeapp\bin\www


Step 4 - Install Dependencies


Next we need to install dependencies, so for this we have to run following command. This command will install required dependencies in your node js express application.


npm install


Step 5 - Install Multer Library


So After successfully install Exppress framework in Node.js application. Now for file upload in Node.js Express application we need to download and install multer library. So in the command prompt we have to run following command.


npm install --save multer


This command will download and install Multer Library in your Node.js Express Application. With the help of Multer library we can able to add file upload feature in Node.js Express library this is because Multer is a Node.js Middleware for handle multipart/form-data, which is mainly used for uploading files to the server.





Step 6 - Create Route for Load File Upload Form


Next we need to create new routes file under routes directory with name fileupload.js and under this file first we need to import express module and multer module and then after we have to create new get route for load file upload form in the browser.

routes/fileupload.js

var express = require('express');

var multer = require('multer');

var router = express.Router();

router.get("/", function(request, response, next){

	response.render('fileupload', {title:'File Upload in Node JS Express using Multer'});

});

module.exports = router;



Step 7 - Set New Route file Rule in app.js


In Node.js Express application if you have create new routes file then you have to define routes under app.js file.

app.js

var fileuploadRouter = require('./routes/fileupload');


In app.js file, first we have to create router variable for particular routes file. And then after we have to define routes url for newly created routes file which you can seen below.


app.use('/fileupload', fileuploadRouter);


Step 8 - Create File Upload File


In this step we need to create new template file under views directory. Under this directory file has been used for display html output in the browser. Under this file, we have to create file upload form for select file from local computer for upload file to server.

views/fileupload.ejs

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title><%= title %></title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-center text-primary mt-3 mb-3"><b><%= title %></b></h1>
            <h4 class="text-center text-danger">Find Source Code Download link in Video Description</h4>
            <div class="card">
                <div class="card-header">File Upload</div>
                <div class="card-body">
                    <form enctype="multipart/form-data" action="/fileupload" method="post">
                        <table class="table">
                            <tr>
                                <th>Select File</th>
                                <td>
                                    <input type="file" name="sample_image" />
                                </td>
                                <td>
                                    <input type="submit" name="submit" class="btn btn-success" value="Upload Image" />
                                </td>
                            </tr>
                        </table>
                    </form>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  </body>
</html>


When we have select file from local computer and click on upload file then it will send file upload request to post routes of fileupload.js file.

Step 9 - Handle File Upload Request


Under this step we have to create post routes for handle file upload request. So we have to create post routes under routes/fileupload.js file.

routes/fileupload.js

var express = require('express');

var multer = require('multer');

var router = express.Router();

router.get("/", function(request, response, next){

	response.render('fileupload', {title:'File Upload in Node JS Express using Multer', message : request.flash('success')});

});

router.post("/", function(request, response, next){

	var storage = multer.diskStorage({

		destination:function(request, file, callback)
		{
			callback(null, './upload');
		},
		filename : function(request, file, callback)
		{
			var temp_file_arr = file.originalname.split(".");

			var temp_file_name = temp_file_arr[0];

			var temp_file_extension = temp_file_arr[1];

			callback(null, temp_file_name + '-' + Date.now() + '.' + temp_file_extension);
		}

	});

	var upload = multer({storage:storage}).single('sample_image');

	upload(request, response, function(error){

		if(error)
		{
			return response.end('Error Uploading File');
		}
		else
		{
			return response.end('File is uploaded successfully');
		}

	});

});

module.exports = router;


Under the post routes, first we have to define multer file upload configuration.

In multer file upload configuration, first we have to define file upload destination details.

After this, we have to rename uploaded file name details and get uploaded file name data.

After define multer file upload configuration, it will upload file under upload directory.

Step 10 - Display Uploaded File


After uploading file, now we need to display uploaded image on the web page. So for display uploaded image on the web page, here we will use session flash message.

So first we need to download and install express-session and connect-flash module under node express application. So for this we have go into command prompt and run following command. So this command will download and install express-session and connect-flash module in node express application.


npm install connect-flash express express-session --save


Next we have to import this both modules under app.js file, which you can seen below.


var session = require('express-session');

var flash = require('connect-flash');


After this, we need to implement connect-flash module and express-session module, so here in app.js file we have to define following configuration.


app.use(session({
  secret : 'webslesson',
  cookie:{maxAge : 60000},
  saveUninitialized : false,
  resave : false
}));

app.use(flash());


After this, we need to store uploaded file name in session flash message, so below you can see that, when web page has been redirect after file upload, then at that time we have store upload file name in session flash message. And in the get routes, we have to also define pass session flash message to template file also, which you can seen below.

routes/fileupload.js

var express = require('express');

var multer = require('multer');

var router = express.Router();

router.get("/", function(request, response, next){

	response.render('fileupload', {title:'File Upload in Node JS Express using Multer', message : request.flash('success')});

});

router.post("/", function(request, response, next){

	var storage = multer.diskStorage({

		destination:function(request, file, callback)
		{
			callback(null, './upload');
		},
		filename : function(request, file, callback)
		{
			var temp_file_arr = file.originalname.split(".");

			var temp_file_name = temp_file_arr[0];

			var temp_file_extension = temp_file_arr[1];

			callback(null, temp_file_name + '-' + Date.now() + '.' + temp_file_extension);
		}

	});

	var upload = multer({storage:storage}).single('sample_image');

	upload(request, response, function(error){

		if(error)
		{
			return response.end('Error Uploading File');
		}
		else
		{
			request.flash('success', request.file.filename);

			response.redirect("/fileupload");
		}

	});

});

module.exports = router;


After this, we want to display upload image under views/fileupload.ejs template file, so in below code you can find how to display uploaded image name from session flash message.

views/fileupload.ejs

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title><%= title %></title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-center text-primary mt-3 mb-3"><b><%= title %></b></h1>
            <h4 class="text-center text-danger">Find Source Code Download link in Video Description</h4>
            <div class="card">
                <div class="card-header">File Upload</div>
                <div class="card-body">
                    <form enctype="multipart/form-data" action="/fileupload" method="post">
                        <table class="table">
                            <tr>
                                <th>Select File</th>
                                <td>
                                    <input type="file" name="sample_image" />
                                </td>
                                <td>
                                    <input type="submit" name="submit" class="btn btn-success" value="Upload Image" />
                                </td>
                            </tr>
                        </table>
                        <div class="mt-5">
                        <% if(message.length > 0) { %>
                            <div class="alert alert-success">
                                File is uploaded successfully
                            </div>
                            <img src="./upload/<%= message %>" class="img-thumbnail" />
                        <% } %>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  </body>
</html>


But in Node.js, we can not directory display images from static directory, so for display images from directory, we have to define rules in app.js file, which you can seen below.


app.use('/upload', express.static('upload'));


So here our code is ready, now we want to check output in the browser, so for this, we have go to command prompt and run following command. This command will start Node.js server.


npm start


And for check output in the browser, we have to hit following url in the browser, which will display file upload form in the browser for upload file in node.js Express application using multer library.


http://localhost:3000/fileupload





0 comments:

Post a Comment