Thursday, August 07, 2014

Handling File Uploads and Downloads In Node.js with Ajax - Express Framework

Uploading the files is important aspect of transferring the data to the server from the client and moving it to the storage to share for downloading and later usage also.However encryption is important aspect of saving the Files safely with pass phrase encryption/and Decryption on Downloading or requesting.These types of Application is done generally in Cloud for user safety for files from Illegal Access.However Node.js doesn't allows you to peep into directories and get download the files where these directories are generally private unless you make it as Public Folder.This is a Main Advantage for us.



Resource : Download Demo files 

Scope:
We are Just going to Upload the Files via Ajax and Retrieve Files from Directory using FS module and make to available for Download.This Application is simple integration of Storing files online and retrieving it from anywhere.


Package.json:

Create package.json and run the installation to create dependencies for our app.
{
  "name": "expressapp",
  "version": "0.0.1",
  "description": "uploading files-Downloading",
  "dependencies": {
    "express": "3.x.x",
    "Jade" : "*"
  }
}

server.js:

Let me Explain about the server.js - i am initializing the app with Express Framework.Then setting the port for the app to listen in my Configuration function by app object of express.For Templating language i have used JADE to parse the variables across the files(view) and set up my View directory.
Then i have initalized with body parser for fetching my posted values via body and setting the limit of upload and keepExtensions of my uploaded file and setting the path for my directory for uploaded files in Server.And i have set up a public static folder for Javascript/CSS files.

So, creating the routes explicitly read here and here to create route url for Node.js Application.I have created four routing URL for index,Upload,Download,listing files.


Replace the Path URL to fetch corresponding files from your directory.For the Convenience I have used JADE  as Templating language ,You must use it carefully since it is space/tab sensitive.Use online Jade input/output for verfiying your syntax.

FileSystem Function :



var fs = require('fs');
fs.readdir('C:\\Users\\S.Shivasurya\\Documents\\node\\expressapp\\tmp\\', function (err, files) {  if (err)
    throw err;
var result=new Array();
 for (var index in files) {
  if(fs.lstatSync("C:\\Users\\S.Shivasurya\\Documents\\node\\expressapp\\tmp\\"+files[index]).isFile())
    result[index]=files[index];
 }
 res.render("files",{ result:result });  //rendering file.jade for viewing
 });

The above functions just read the given directory and fetch all files and save it in an array if it is file and not a directory! refer to node.js docs for more fs functions

Script.js (Ajax file Upload):


A Third Party plugin for AJAX upload with progress bar:



Jade for looping Array :

file.jade to list out the Files in directory while accessing /file route


extends layout
title files
block content
  div.container
    div.content   
        ul
          - each results in result
            li= results
            input(type='submit', value='Download',id=results,class='download')

  div.footer

Index.jade:


extends layout

block content

  div.container
    div.row
      div.span12
        form(method='post', action='/')
          legend express-upload-progress
          input(type='file', name='myFile', id='myFile')
          p
          div.form-actions
            input.btn.btn-primary(type='submit', value='Submit')
    hr
    div.row
      div.span12
        div.progress.progress-striped.active.hide
          div.bar(style='width: 0%')
    div.row
      div.span12
        div.alert.hide
          button.close(type='button', data-dismiss='alert') x
          span
            strong.message

Layout.jade:


doctype html
html
  head
    title express-upload-progress
    link(rel='stylesheet', href='/stylesheets/bootstrap.min.css')
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content
    script(src='/javascripts/jquery-1.9.1.min.js')
    script(src='/javascripts/bootstrap.min.js')
    script(src='/javascripts/scripts.js')

Download script as client javascript :

This is a simple script that can post the filename we request and download the file from Node.js express routes /download.i am not doing any Ajax operation here.just submiting POST request to server for downloading a file.

on clicking the download button,Jquery request for the file and downloads on the browser automatically.


$(document).ready(function(){
  $(".download").click(function(e){
   var filedata=this.id;
  $('<form action="/download" method="POST">' + 
    '<input type="hidden" name="file" value="' + filedata+ '">' +
    '</form>').submit();

    });
});

I Have tested on Localhost node.js server ,Have a try with demo files provided,If any error/Bug in Code/Article post as comment/mail me s.shivasurya@gmail.com.connect with me via Facebook/Twitter for help.Share is care.report for bugs.

0 comments:

Post a Comment

feel free to post your comments! Don't Spam here!