File upload in nodeJs with progress bar

Hello friends, In this post i am going to show you a basic example of file uploading system in nodejs,
nodejs-file-uploader
Make sure you already have npm, nodejs, express installed in your system.

Follow the below instruction to installing all packages in ubuntu

sudo aptget install nodejs

sudo aptget install npm




Installing and configuring express follow below instruction given on express official website  http://expressjs.com/starter/installing.html

Technology used: NodeJs, expressJs, bootstrap, jquery

Lets start step by step creating files.

Step-1: Create package.json file

package.json

{
"name": "NodejsFileUpload",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "~3.4.0",
"jade": "*"
},
"engines": {
"node": "0.10.x"
}
}

Step-2: Create view file here i am using jade templating engine to create view.
learn more about jade from here http://jade-lang.com/

views/fileUpload.jade

extends layout
block content
h3 Simple file upload in nodeJs with progress bar
form(name="fileUpload", action="/fileUpload",enctype="multipart/form-data", method="post",role="form", class="form-inline")
.form-group
label Choose image to upload:
input(name="uploadfile", type="file", id="myFile")
span(style="color:red") Upload only image file (PNG, JPEG, GIF)
.form-group
input(value="UPLOAD", type="button", class="btn btn-primary")
div(class="progress",style="display:none;margin-top:10px;")
div(class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100") 0%
div
h3 List all uploaded files
p(id="msg")
#files

Step-3 Create another view file under view folder to show list of uploaded files.

views/filelist.jade

extends layoutblank
block content
each value in fileList
div(style="width:210px;float:left")
a(href="./files/"+value, target="_blank")
img(src="./files/"+value, height=200, width=200)
span #{value}
a(href="javascript:void(0)",file=value, id="delete") Delete

Step-4: Create client side js file under public/js folder to write jquery
Note: The progress bar requires modern browsers that support HTML5 tags and XMLHttpRequest is a new HTML5 feature that adds more functionality to AJAX requests for transferring data between a client and a server.

public/js/fileupload.js

 
$(function() {
$("#files").load("filelist");
$("input[type='button']").click(function() {
var formData = new FormData();
if($('#myFile').val()=='') {
alert("Please choose file!");
return false;
}
$('div.progress').show();
var file = document.getElementById('myFile').files[0];
formData.append('uploadfile', file);
var xhr = new XMLHttpRequest();
xhr.open('post', 'fileUpload/', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentage = (e.loaded / e.total) * 100;
$('div.progress div').css('width', percentage.toFixed(0) + '%');
$('div.progress div').html(percentage.toFixed(0) + '%');
}
};
xhr.onerror = function(e) {
alert('An error occurred while submitting the form. Maybe your file is too big');
};
xhr.onload = function() {
var file = xhr.responseText;
$('div.progress div').css('width','0%');
$('div.progress').hide();
showMsg("alert alert-success", "File uploaded successfully!");
$('#myFile').val('');
};
xhr.send(formData);
return false;
});
function showMsg(className, msg) {
$("#msg").fadeIn();
$("#files").load("filelist");
$("#msg").addClass(className);
$("#msg").html(msg);
$("#msg").fadeOut(3000,function() {
$("#msg").removeClass(className);
});
}
$(document).on('click','#delete',function() {
$(this).attr('href','javascript:void(0)');
$(this).html("deleting..");
var file = $(this).attr("file");
$.ajax({
url:'deleteFile/'+file,
type:'GET',
data:{},
success:function(res){
showMsg("alert alert-danger", "File deleted successfully!")
}
});
});
});

Step:5- Now turn for server side coding. Create file config.js file write all configuration here to set the path of TEMP folder and directory where have to upload files

config.js

exports.TEMPDIR = './public/temp';
exports.UPLOADDIR = './public/files/';

Step-6- Now turn to create main file which will create server for you & write file upload and delete code here

app.js

/*
* Author: Rohit Kumar
* Date: 24-07-2014
* Website: iamrohit.in
* App Name: Node File Upload
* Description: File upload module in nodeJs with progress bar
*/
/**
* Module dependencies.
*/
var config = require('./config');
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var app = express();
// all environments
app.set('port', process.env.PORT || 5000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
process.env.TMPDIR = config.TEMPDIR;
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', function(req, res) {
fs.readdir(config.UPLOADDIR,function(err, list) {
if(err)
throw err;
res.render('fileUpload',{fileList:list});
});
});
app.get('/deleteFile/:file', function(req, res){
var targetPath = config.UPLOADDIR+req.param("file");
fs.unlink(targetPath,function(err) {
if(err) {
res.send("Error to delete file: "+err);
} else {
res.send("File deleted successfully!");
}
})
});
app.get('/users', user.list);
app.get('/fileUpload', routes.fileUpload);
app.get('/filelist', function(req, res) {
fs.readdir(config.UPLOADDIR,function(err, list) {
if(err)
throw err;
res.render('filelist',{fileList:list});
});
});
app.post('/fileUpload', function(req, res) {
var tempPath = req.files.uploadfile.path;
var targetPath = config.UPLOADDIR+req.files.uploadfile.name;
fs.rename(tempPath, targetPath, function(err) {
if(err) {
//res.send("Error found to upload file "+err);
var msg = "Error found to upload file "+err;
var type="error";
} else {
//res.send("<b>File uploaded to "+targetPath+" ("+req.files.uploadfile.size +" bytes)</b>");
var fileSize = req.files.uploadfile.size/1024;
var msg = "File uploaded to "+targetPath+" ("+(fileSize.toFixed(2)) +" kb)";
var type="success";
res.send(req.files.uploadfile.name);
}
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

Just click on demo button to see the live working demo and also you can download source code by clicking on source code button.

Hope this will help you to create file uploading system in nodejs..!!

20+ FREE Nodejs File Upload Scripts

Are you looking for Nodejs File Upload for your web based application. If yes then in this post I am going to share hand picked top rated Nodejs File Upload. You can use these popular Nodejs File Upload to make your web application more awesome.


Nodejs File Upload

Following are the list of popular top rated hand picked Nodejs File Upload.

  • lite-uploader:- Lightweight file uploader for NodeJS and jQuery with support for drag/drop, basic and custom validators and hooks for…
  • uploader:- File sharing platform built on Nodejs and Amazon S3
  • file-upload-with-angularjs-and-nodejs:- File Upload using Angular and Node
  • nodejs-mongodb-file-uploader:- a simple HTML/JQuery file upload system that is powered by node.js and MongoDB’s GridFS
  • NodeJS-File-Upload-Examples:- Showing working implementations of Uploadify, Swfupload and Valums File-Uploader
  • apollo-upload-examples:- A full stack demo of file uploads via GraphQL mutations using Apollo Server and apollo-upload-client.
  • gulp-ftp:- [DEPRECATED] Upload files to an FTP-server
  • node-file-uploads:- This is example for uploading files in nodejs with multipart and jquery
  • form-data:- A module to create readable `”multipart/form-data”` streams. Can be used to submit forms and file uploads to other we…
  • nodeJs-file-upload:- File upload in nodeJs with progress bar
  • upLoadFiles:- nodeJs——Multi file upload
  • mongoose-file:- Mongoose plugin adding a file field to a schema – useful for nodejs file uploads
  • Loopback-Upload:- This project is for demonstrating how to implement file upload functionality using the NodeJS framework LoopBack, cre…
  • upload-file:- 使用element-uiçš„upload组件实现上传图片至七牛云
  • fileupload-nodejs-gridfs-angular2:- File Upload application with Nodejs, GridFS and Angular 2
  • File-Upload-Using-Multer:- File upload using Node.js Express.js and Multer Middleware
  • nodejs-ajax-upload-example:- 一个基于七牛云存储 NodeJS SDK å’Œ jQuery-File-Upload 开发的 Ajax 上传示例程序
  • file-upload:- ajax +NodeJS 实现图片上传的demo
  • nodejs-basic-file-upload:- Basic File Upload using Node.js with Percentage (no ajax)
  • netsuite-uploader-util:- Helper library for uploading files from your local computer into the NetSuite File Cabinet from nodejs.

I Hope you liked Hand-picked list of Nodejs File Upload, Don’t forget to Subscribe My Public Notebook for more useful Hand-picked PHP and MySql code examples, tutorials and articles.

5 Replies to “File upload in nodeJs with progress bar”

  1. Hello rohit…..
    I have not idea about JSon and JNode..Can you give a code in PHP,HTML,CSS for showing progress bar…for file uploading i used this code in php ….
    <?php
    if(iseset($_post['sub']))
    {
    $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];
    $folder="uploads/";

    // new file size in KB
    $new_size = $file_size/1024;
    // new file size in KB

    // make file name in lower case
    $new_file_name = strtolower($file);
    // make file name in lower case

    $final_file=str_replace(' ','-',$new_file_name);

    /////////////////file end////////////////////////////

    $con= mysqli_connect("localhost", "root", "", "");

    if(!$con)
    {

    die("not connected");
    }
    if(move_uploaded_file($file_loc,$folder.$final_file))
    {

    $x=mysqli_query($con,"insert…………..");
    }

  2. I am getting error – Failed to load resource: the server responded with a status of 404 (Not Found) in xhr.Send(formData);

    Please help…

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.