File upload in nodeJs with progress bar
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 apt–get install nodejs
sudo apt–get 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
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();
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;
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.
file-uploader:- Learn how to build an AJAX file uploader using NodeJs
s3-angular-file-upload:- Example of S3 file upload using ng-file-upload, angular, nodejs
FileUploader:- 基于nodejs以åŠhtml5的拖曳ä¸Å ä¼
File-upload-Angular2-Nodejs:- File upload with angular 2 and node.js
express-fileupload:- Simple express file upload middleware that wraps around busboy
simple-file-uploader:- A file uploader written using HTML5 and Node.js. It can upload both to a local directory on the server or to an AWS S…
fileupload-nodejs:- MongoDB file upload using NodeJS and Mongo GridFS
nodejs-file-upload-multer:- multer文件ä¸Å ä¼ Ã¥®Å¾Ã¤¾‹
embetacloud:- directly upload files to google drive
DropIt:- DropIt is a File Uploader built with nodejs, Upload, get a link, and share your files with anyone easily.
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.
Post a Comment