File Upload Using Angular Js and Node Js

AngularJs
Node js
file upload
multer module

Here is the code for file upload using Angular Js (1x) and Node Js. By using below code we can upload any type files like .pdf,.doc,.docx,.exe.mp4,.avg (files, videos, audios, any .exe files)

Creating the Directive for uploading file.

angular.module('uploadFile’').directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);

List of other types of custom directives

  1. E for Element name
  2. A for Attribute
  3. C for Class
  4. M for Comment

The above directive is  Attribute type of directive (restrict: 'A').

Here is the HTML code.

<span><label for="file_upload1_videofile" class="btn btn_md btn-success btn-sm">Attach</label>

<input type="file" id="file_upload1_videofile" style=”display:none” file-model="myFile" onchange="angular.element(this).scope().CheckuploadFile()" /><br>

Here input type file is not visible, by using label we can trigger input type file for better UI. By using onchange automatically uploaded the file and return the response.

Here is the Controller Code

$scope.CheckuploadFile = function(){
	setTimeout(function(){$scope.uploadFile();}, 1000);
};
	
$scope.uploadFile = function(){
var file = $scope.myFile;
	var uploadUrl = "/savefiles";
       	var fd = new FormData();
        	fd.append('file', file);

        $http.post(uploadUrl,fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(resp){
		if(resp.status == 0){
			alert('Error in uploading video');
			return false;
		}else{
			alert('Video Attached Successfully');
			$scope.videos.video_name = resp.savedpath;
		}
        })
        .error(function(){
			console.log("error!!");
			alert('Error in uploading video');
			return false;
        });
    };

In above Code,
In uploadFile function fd.append('file', file);, The second file (variable) is contain uploaded file. The first file (string) storing chunks of uploaded file.
uploadUrl is the service/api URL.
resp.savedpath is new filename for uploaded file getting from server side.
Place headers in $http call like headers: {'Content-Type': undefined} to upload file.

Checking file type validation uploaded file

After attaching file we can check with $scope.myFile. $scope.myFile variable contain all the information about uploaded file, by using below if conditions we can validate type of uploaded file.

var file = $scope.myFile;
if(file.type == 'image/jpeg'){
   alert('Image file is uploaded');
}
if(file.type == 'application/pdf'){
   alert('PDF file is uploaded');
}
if(file.type == 'video/mp4'){
   alert('Video MP4 file is uploaded');
}
if(file.type == 'video/3gpp'){
   alert('Video 3gpp file is uploaded');
}
if(file.type == 'application/x-msdownload'){
   alert('Windows .exe file is uploaded');
}

Or we can restrict file types from html, below is the sample html codes for file type restriction.

<input type="file" name="pic" accept="image/*">
<input type="file" name="pic" accept="'video/*">
<input type="file" name="pic" accept="'application/*">

Checking file size limit validation uploaded file

By using $scope.myFile we can check uploaded file size. By default the size should be in bytes. Below is the code for checking file size,

var file = $scope.myFile;
if(file.size >= 5000000){
   alert('Allow file Size should be 5 MB');
}

In Node js,
Here we need to install multer,path modules to upload file.
Below is the command for install multer module is

npm install multer --save // install locally and update in package.json file

Below is the command for install path module is

npm install path --save // install locally and update in package.json file

Below is the Settings for Storage variable and Update function to upload.

var Storage = multer.diskStorage({
     destination: function(req, file, callback) {
         callback(null, "public/videos/");
     },
     filename: function(req, file, callback) {
		var ext = path.extname(file.originalname);
		callback(null, “new file name”);
     }
 });

By using file.originalname we will get original file name (uploaded file name).
By using this callback(null, “new file name”); we can rename to uploaded file. Whatever the name given here, the attached file will be created with this name.
By using this callback(null, "video path to save file"); we can set path for saving the file.
By using this path.extname(file.originalname); we can get uploaded file extension.

var upload = multer({ storage: Storage}).single('file');

upload is the multer function.
.single('file') is single file upload and file is the array which is coming from angular controller please refer above controller code.

If we are upload multiple files then use upload function like

var upload = multer({ storage : storage }).array('files',2);

For example
In controller, we append formdata to 'file' like fd.append('file', file);.
In node js upload function like .array('file',2); or .single('file');.

In controller, we append formdata to 'uploadfile' like fd.append('uploadfile', file);.
In node js upload function like .array('uploadfile',2); or .single('uploadfile');.

router.post('/savefiles, function(req, res, next) {
	Try{
// calling upload function passing 2 parameters and 1 callback function
     upload(req, res, function(err) {
        if(err){
		console.log(err);
		var res_data = {status :0,message:'error while uploading'};
		res.send(res_data);
        }else{
		var fileName = "videos/" + req.file.filename;
		var res_data = {status :1,message:'Uploaded Successfully',savedpath:fileName};
		res.send(res_data);
	}
     });
	}catch(e){
		console.log("Error : " , e);
	}
});

Here we are passing entire req,res to upload function. By using req.file.filename we will get new file name of uploaded file.

Note : Before moving to Prod server check what is the maximum file upload size of your server. If it is 5MB,2MB then increase upload limit as per your requirement. Otherwise you will get 413 Error. And also check maximum upload limit of your server side programming language like PHP,Node Js, ...etc.

In Node js, we can increase maximum upload size like below code,

var express = require('express');
var app=express();
app.use(bodyParser.json({limit: '500mb'})); // parse application/json 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true, limit: '500mb' })); // parse application/x-www-form-urlencoded

In php, we can increase maximum upload size like below code,
In php.ini file change the value from upload_max_filesize = 10M to upload_max_filesize = 500M. Then restart the appache server.

 

In nginx,
Open the path # /etc/nginx/sites-avaliable/
Open default file, then add below line into your nginx roues file

server {

 listen 80;

 listen [::]:80;

 root /var/www/mysite;

 index index.php index.html index.htm;

 server name domain.com www.domain.com;

 location / {

   client_max_body_size 500m;

  }

}

This is only for particular site, if you want to increase upload size complete nginx

Open /etc/nginx/nginx.conf, add below lines in nginx file like below

http {
   client_max_body_size 500M;
}

Then restart the nginx server.

 

You might also like:

Example for Conditional Operator in php

16-04-2017 php Conditional Operator example

How to use http-post request in node js

14-03-2017 http-post module node js

How to find Angular Errors

06-03-2017 errors angularjs exceptionHandler

Filter for replace text in Angular Js

05-03-2017 filter replace angular js

Send Mail in Node Js

21-02-2017 node js mail npm module