File upload using angularjs and nodejs multer module

Cronjob

Hey guys, In this tutorial we are going to create an angularjs web application which will upload user selected file with the help of nodejs multer module.

Let's have a look on folder structure of the application.

node_modules
public
    index.html
    server.js
package.json
package-lock.json

 

so we are starting with first file, index.html

 

 
<html ng-app="myApp">
    <div ng-controller = "myCtrl">
        <input type = "file" file-model = "myFile"/>
        <button ng-click = "uploadFile()">Upload File</button>
    </div>
</html>
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.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]);
            });
        });
    }
};
}]);
 
myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
 
        .error(function(){
        });
 
    }
 
}]);
 
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
    $scope.uploadFile = function(){
        var file = $scope.myFile;
        var uploadUrl = "/savedata";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };
}]);
 
</script>
 

 

In the above file, we have input field for choosing file from user and at bottom under script tag we have created angular app. From html file angular method uploadFile is calling, which uploads file with $http module of angular.

Now lets discuss server side related task, package.json

 

 
{
        "name": "angularjs-file-uploader",
        "version": "1.0.1",
        "description": "Simple file uploader demo using NodeJS",
        "main": "server.js",
        "scripts": {
                "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "Suraj Roy",
        "license": "ISC",
        "dependencies": {
            "express": "^4.13.4",
            "http": "0.0.0",
            "multer": "^1.1.0",
            "path": "^0.12.7"
        }
}
 

 

in the above file we have details related to our nodejs app.

 

 
let express = require('express'),
app = express(),
path = require('path'),
http = require('http'),
multer = require('multer');
 
let storage = multer.diskStorage({
    destination: './uploads/',
 
    filename: function (req, file, cb) {
        cb(null, file.originalname.replace(path.extname(file.originalname), "") + '-' + Date.now() + path.extname(file.originalname))
    }
})
 
let upload = multer({ storage: storage })
 
app.use(express.static(path.join(__dirname, 'public')));
 
app.set('port', process.env.PORT || 3000);
 
app.post('/savedata', upload.single('file'), function(req,res,next){
    console.log('File Uploaded Successfully! ', req.file.filename);
    res.send({"statusCode":200,"statusMessage":"file uploaded successfully!"});
});
 
http.createServer(app).listen(app.get('port'), function(){
        console.log('Server listening on port: ' + app.get('port'));
});
 

 

In the above js file which actually does the file uploading at server end with help of multer module. 

This way we can upload file using angularjs and nodejs. If still you find any confusion, You can write us at demo.jsonworld@gmail.com. 

You can download complete code from here. Download Code