Uploading Image with AngularJs + saving with NodeJs

This is a quick snippet to uploading a file using AngularJs to NodeJs backend.

frontend

Inside controller.js, include a service called $upload. (check out $upload github page for more implementation).


angular.module('myapp.controllers', [])                    .controller('MainCtrl',
    [       '$scope', '$upload', 
    function($scope, $upload) {
    $scope.rootUrl = "yourRootUrl";
    $scope.upload = $upload.upload({
                            url: $scope.rootUrl+'/uploadImage',
                            method: 'POST',
                            file: file,
                        }).progress(function(evt) {
                        }).success(function(data, status, headers, config) {
                        };
            });

backend

On the server side, include this the three modules fs, path and crypto inside the controller that accepts /uploadImage. (crypto is not required, but it will come in handy.)
This method saves the uploaded images inside a public path that is used in a desired application, which is why the file's permission needs to be changed at the very end. It also assumes the uploaded file is ".jpeg".

var fs = require('fs-extra');
var path = require('path');
var crypto = require('crypto');

uploadImage: function(req, res){
    var destPath = path.join(__dirname, "../../assets/images/");
    var originalFilename = req.files.file.originalFilename;
    var hashName = crypto.createHash('md5').update(originalFilename).digest('hex') + ".jpeg"; 
    var writeStream = req.files.file.ws;

   //if the file already exists in the path, then create a random file name from hashName.
  while (fs.existsSync(destPath+hashName)) {
    hashName = hashName.substring(0, hashName.length - 5);
     var rnd = crypto.randomBytes(3),
        value = new Array(3),
        len = hashName.length;
    for (var i = 0; i < 3; i++) {
        value[i] = hashName[rnd[i] % len];
      };
      hashName = hashName + value.join('') + ".jpeg";
    }
 fs.copy(writeStream.path, destPath+hashName, function (err) {
      if (err) return res.send(err);
      fs.chmodSync(destPath+hashName, '755'); //there is probably a better solution, I have to change the permission to access the file from public images directory 
      fs.remove(writeStream.path, function(err){
        if (err) return res.error(err);
      });
    });
  });
}

This whole snippet is a compilation of google searches, but I had to seperate the searches as I was putting the whole thing together. Hopefully it gives a quick start to your project, and if there is a better implementation, leave a comment : )

comments powered by Disqus