Best practice to Upload file to the Server using AngularJS and NodeJS

Posted By : Rahul Sarkar | 10-Jun-2017

Here I am going to describe you the best practice to upload file to the server using Angular and Node JS.

First we have to create a input box in HTML to select the file.

Then we have to write code in angular to create the request to upload.

   var uploadUserFile = function(file) {
      var uploadFileUrl = "/api/v1/upload/;
      var uploadFile = Upload.upload({
         url: uploadFileUrl,
         file: file
      });
  }       

Now set the router path to call the download function of backend

router.post('/api/v1/upload/', FileUploadController.saveFile);

Now create a controller in Node:

var UploadService = require("uploadService").UploadService; 
module.exports.CompanyPoliciesController = (function() {
    var saveFile = function(req, res) {
        UploadService.saveFile(req.files.file, res);
    }
    return {
        saveFile: saveFile
    };
})();

Now create service method to upload your file to the server:

module.exports.UploadService = (function() {
    var uploadCompanyPolicyFileToServer = function(file, res) {
        var fs = require('fs');
        var path = require('path'); // to create a path seperator
        var mkdirp = require('mkdirp'); // to create directory
        var uuid = require('node-uuid');
        var filePath = '/opt/userFiles/';

        mkdirp(filePath, function (err) {
            if (err) {
                configurationHolder.ResponseUtil.responseHandler(res, err, err.message, true, 400);
            } else {
                var target_path = filePath + file.originalFilename,
                tmp_path = file.path;
                var source = fs.createReadStream(tmp_path);
                var dest = fs.createWriteStream(target_path);
                source.pipe(dest);
                source.on('end', function(err) {
                    if (err) {
                        configurationHolder.ResponseUtil.responseHandler(res, err, "failed to upload " + file.name, true, 400);
                    } else {
                        configurationHolder.ResponseUtil.responseHandler(res, {}, File upload successfully, true, 400);
                    }
                });
            }   
        });
    }
    return {
        saveFile: saveFile
    }
})();

 

Thank You !!!

About Author

Author Image
Rahul Sarkar

Rahul is an intellectual web app developer, he has good knowledge of C, Java, Java Script, Jquery. Apart from this he likes to travel and explore new places.

Request for Proposal

Name is required

Comment is required

Sending message..