Uploading Files using node.js , expressJS and formidable module of node.js






Overview

We will learn how we can upload files using node.js , express and formidable module of node.js for backend ; HTML5 for frontend and Bootstrap 3.3.7 and CSS 3 for styling. The uploaded files will be stored in the data directory created in the root directory of the project.

Prerequisites

  1. Node.js installed : You can download it here .

Directory Structure

Frontend

Let's start by creating a simple static form in HTML5 . This form is having 2 fields :

  • Choose file : This field is used to select the file to be uploaded.
  • upload : This field is used to upload the selected file.

We are starting with the coding part now, Although the code is self explanatory but informative comments are provided where ever needed.
  1. index.html :
    										
    <!DOCTYPE html>
    <html>
    <head>
        <title>Simple file Upload | Nodejsera | Code Snippet</title>
    	<!-- Including bootstrap for styling -->
    	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    	<!-- Including external css -->
    	<link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
    
    	<br>
    	<Br>
    	<div class="row">
    		<div class="col-md-2">
    				<!-- EMPTY div -->
    		</div>
    		<div class="col-md-8 form">
    			<br>
    			<br>
    			<!-- Form starts here -->
    			<form action="/" enctype="multipart/form-data" method="post">	
    				<!-- Field to choose the files to be uploaded -->
    				<label class="up_styles">
    					<input type="file" name="upload" multiple />
    				</label>
    				<br>
    				<!-- Button to upload the choosed files -->
    				<input class="sub" type="submit" value="Upload">
    			</form>
    			<br>
    			<br>
    		</div>
    		<div class="col-md-2">
    				<!-- EMPTY div -->
    		</div>
    	</div>
    </body>
    </html>		
    										
    									

Styling with CSS3


  1. style.css :
    										
    @import url('https://fonts.googleapis.com/css?family=Coda');
    /**
    	font-family: 'Coda', cursive;
    **/
    
    .form{
    	padding:20px;
    	border : 2px solid #3385ff;
    	border-radius: 15px;
    	text-align:center;
    }
    
    input{
    	font-family: 'Coda', cursive;
        width: 100%;
    	font-size: 30px;
        padding: 12px 20px;
        margin: 8px 0;
        border: none;
        border-bottom: 2px solid #3385ff;
    }
    
    input[type=submit]{
    	font-family: 'Coda', cursive;
    	width: 100%;
        background-color: #66a3ff;
        border: none;
        color: white;
        padding: 16px 32px;
        text-decoration: none;
        margin: 4px 2px;
        cursor: pointer;
    	border-radius: 15px;
    }
    input[type=submit]:hover {
    	font-family: 'Coda', cursive;
    	width: 100%;
        background-color: #3385ff;
        border: none;
        color: white;
        padding: 16px 32px;
        text-decoration: none;
        margin: 4px 2px;
        cursor: pointer;
    	border-radius: 15px;
    }	
    										
    									

Backend with node , express & formidable


  1. Installing the required packages :
    • express :
      												
      >npm install express --save
      												
      											

    • Formidable :
      												
      >npm install formidable --save
      												
      											

  2. server.js :
    										
    var express = require('express');
    var formidable = require('formidable');
    const path = require('path');
    
    var app = express();
    
    app.use('/', express.static(path.join(__dirname, 'public')))
    
    app.get('/', function (req, res){
        res.sendFile(__dirname + '/public/index.html');
    });
    
    app.post('/', function (req, res){
        var form = new formidable.IncomingForm();
    
        form.parse(req);
    
        form.on('fileBegin', function (name, file){
            file.path = __dirname + '/data/' + file.name;
        });
    
        form.on('file', function (name, file){
            console.log('Uploaded ' + file.name);
        });
    
        return res.json(200, {
    							result: 'Upload Success'
        });
    });
    app.listen(3000, () => console.log('Server app listening on port 3000!'))	
    										
    									

Run the code

We can run the server.js using the following command :

													
>node server.js
													
												

and open 127.0.0.1:3000 .

Screenshots

  1. index.html
    URL is : http://127.0.0.1:3000/public/index.html

    Upload file frontend

  2. SnapShot of the backend up and running :

    Screenshot of backend up and running

  3. Successful upload acknowledgement :

    Successful upload acknowledgement

You can check your data directory to see the uploaded content.

Summary

In this article we learned how to use node.js , express and formidable module of node.js to upload files with a HTML 5 frontend.

Repository

Get it from Github :




30 days of node - Nodejs tutorial series