articles

Home / DeveloperSection / Articles / Upload and Download File in Node.JS

Upload and Download File in Node.JS

Anchal Kesharwani56217 20-Sep-2014

In this article, I’m explaining the concept of upload and download file in node.js. In this article create an express project to upload and download the file. 

First know that what is upload and download. Upload is a utility to upload your file one computer to another computer. Upload provides the facility to easily send data one place to another place.

Downloading is the utility to download a file from the network that means you receive the information from another computer.

Let’s create a sample to uploading and downloading in node.js: 

Step 1 Create an express project

 

First create an express project from command prompt as express command as like this:

Upload and Download File in Node.JS

After create express project install dependency. 

Step 2 Install Dependency

 

Now install the al dependency which is required. Let’s now see the dependency and add the package.json:

{ 
  "name":
"UploadAndDownload",
  "version":
"0.0.1",
  "private": true,
  "scripts": {
    "start": "node
./bin/www"
  },
  "dependencies": {
    "express":
"~4.2.0",
    "body-parser":
"~1.0.0",
    "jade":
"~1.3.0",

"connect":"~2.14.4"
  }
}

 

These all necessary package that work in the project. Now write in the package.json file and install it by npm install command. 

Step 3 Create User Interface and Styles

 

Let’s create the user interface that show how’s looking your program in the browser. You should this is create jade engine. Let’s open up the /views/index.jade file and create a form for upload and create a tablefor download. There are the following code that replace it in the index.jade file:

extends layout
block content
  h1= title
  p Welcome to #{title}
  form(method="post", action="/upload", enctype='multipart/form-data')
   input(type="file", name="image", id="image")
   input(type="submit", value="Upload", class="button-style")
   br
   span#message
  br
  br
  br
  div#download  table
    thead
     th File Name
     th Download
    tbody

 

That create your user interface. I’m also add /public/style.css file some style to improve the user interface:

h1
{
       font-family: "Monotype Corsiva";
    color: Black;
}
.button-style
{
      color: rgb(245, 245, 245);   background-color: rgb(34, 80, 226);
    height: 45px;
      width: 130px;
      border-radius: 5px;
      font-weight: bold;
}

This add for button and the heading to add style. If don’t add it then update the index.jade file a line code:

input(type="submit", value="Upload")

 

So application is ready. Let’s see that:

Upload and Download File in Node.JS

 

Let’s move on the coding part.

 

Step 4 Change in app.js

 

Let’s we only few things and very different normal express project to create the main file and run from the node app.js command. Let’s replace all code by the following code:

// add the modules
var express  = require('express');
var path = require('path');  // add path to set and get
var fs = require('fs');  // add filesystem
var connect = require('connect');
 
var app  = express();
var port = process.env.PORT || 3000; // run on the port 3000
 
 
var routes = require('./routes/index');
var users = require('./routes/users');
 
var app = express();
 
// view engine setup and directory name
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
 
//add comfoguration
app.use(express.static(__dirname + '/public'));
app.use(connect.cookieParser());
app.use(connect.logger('dev'));
app.use(connect.bodyParser());
app.use(connect.json());
app.use(connect.urlencoded());
 
app.use('/', routes);
app.use('/users', users);
 
// listen at port 3000
app.listen(port);
console.log('The Server runs on port ' + port);

 

This is necessary for the application. Let’s cod for upload. 

Step 5 Upload Code

 

Our index.js file handles all the HTTP requests such as GET, POST. We need to create our own routes to handle image upload and to view the image. We are importing the defined function using require(). The image upload is defined using POST method. When we receive the image in the server we write the image in uploads directory. To view the image file in browser we are defining a separate route with GET method, it reads the image from uploads directory and display it in browser.

 

Let’s add in the /views/index.js file:

var fs = require('fs'); 
router.post('/upload', function(req, res) {
  var path=require('path'); // add path module
    fs.readFile(req.files.image.path, function (err, data){ // readfilr from the given path     var dirname = path.resolve(".")+'/uploads/'; // path.resolve(“.”) get application directory path     var newPath = dirname + req.files.image.originalFilename; // add the file name     fs.writeFile(newPath, data, function (err) { // write file in uploads folder     if(err){     res.json("Failed to upload your file");     }else {   res.json("Successfully uploaded your file"); }
}); });
});
router.get('/uploads/:file', function (req, res){   var path=require('path');     file = req.params.file;     var dirname = path.resolve(".")+'/uploads/';     var img = fs.readFileSync(dirname + file);     res.writeHead(200, {'Content-Type': 'image/jpg' });     res.end(img, 'binary'); });

 

By this we can easily upload all file either this was image or text files. Let’s move for downloadin. 

Step 6 Get All Files from uploads directory and Show in Table

 

It is necessary get files from any directory to give the download. Here, I give the uploads directory to all download files. Let’s add the code in the /views/index.js file:

router.get('/download', function(req, res) { // create download route   var path=require('path'); // get path   var dir=path.resolve(".")+'/uploads/'; // give path     fs.readdir(dir, function(err, list) { // read directory return error or list     if (err) return res.json(err);     else                 res.json(list);                 }); });

 

This get the all files that contains uploads folder. But how to show it in the table for downloads. There was the big problem but don’t worry. Let’s open your /views/layout.jade file and add the jquery file and global.js file.

doctype html html   head         title= title         link(rel='stylesheet', href='/stylesheets/style.css')     body         block content // add jquery and global.js file 
        script(src='http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')         script(src='/javascripts/global.js')

 

And after that create the global.js file in the /public/javascript/ location. Let’s create it with the given code:

// document ready call itself $(document).ready(function(){         populateTable(); // populateTable function 
              }); // Add a function show files with in the table function populateTable() {     // Empty content string     var tableContent = ''; // it a variable     // jQuery AJAX call for JSON     $.getJSON( '/download', function( data ) { // get files as data             for(var item in data) { // one by one get and add fortable
              tableContent += '<tr>';                 tableContent += '<td>' + data[item] + '</td>'; // this file name column
              tableContent += '<td><a href='+'/'+data[item]+'>' + data[item]+ '</a></td>'; // this was the link column
          }
// this all added into the tableContent variable         $('#download table tbody').html(tableContent); // add into the table     }); };

This is load into the table all file with its links. 

Step 8 Download Code

 

This step to create the download file. This is the simple get the file and use res.download() method download it. Let’s add code in the /routes/index.js file:

// Add this route for download it 
router.get('/:file(*)', function(req, res, next){ // this routes all types of file
  var path=require('path');
  var file = req.params.file;
  var path = path.resolve(".")+'/uploads/'+file;
  res.download(path); // magic of download fuction
});

By this code simply download file in the application. 

Step 9 Run Application 

Let’s ready for run with complete functionality. Now run the application by the node app.js command. Let’s see this:

Upload and Download File in Node.JS

 

Let’s upload a file:

Upload and Download File in Node.JS

Now click on the upload button it redirect in the upload route and give message successfully uploaded. Let’s check in the upload directory:

Upload and Download File in Node.JS

Now check the download let’s refresh the page it add the file for downloading. Let’s download it:

Upload and Download File in Node.JS

This fil was successfully download it. It’s working. 

I hope that this article is helpful for you. Thanks!

 

 


Updated 06-Aug-2020

Leave Comment

Comments

Liked By