0

I am fresher to using Angular js and node js. I am doing File Uploading process by angular and node js. I already create directives and services by watching some tutorial. But in services Form data is not posting on NodeJs server. Here is following code file by file:-

Here is my Directive :-

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]);
                });
            });
        }
    };
}]);

Here is service file code :-

myApp.service('multipartForm', ['$http', function($http){
    this.post = function(uploadUrl, data){
        var fd = new FormData();
        for(var key in data)
            fd.append(key,data[key]);

        console.log(fd);
        $http({
            url: uploadUrl,
            method: 'POST',
            headers: { 'Content-Type': undefined },
            transformRequest: angular.identity,
            data: JSON.stringify(fd)
        }).
        success(function(data) {
            console.log('success');
        }).
        error(function(data, response) {
            console.log(response + " " + data);
        });
    };
}]);

This is my angularjs code where i defined all methods :-

var myApp = angular.module('myApp', []);

    myApp.controller('saveJsonDemo',['$http','$scope','multipartForm',function($http,$scope,multipartForm){

        $scope.formData = {};
        $scope.saveJson = function() {
        var uploadUrl = '/savedata';
        console.log($scope.formData);
        multipartForm.post(uploadUrl, $scope.formData);
    };

    }]);

When i post data though this service to node js server, and i console.log req.body and rex.files is becomes blank. Where is the problem in my code. Here is my Node js server file (app.js)

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var fs = require('fs');
var multer = require('multer');
var done       =       false;

// all environments
app.use(multer({dest: './uploads/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));

app.set('port', process.env.PORT || 3000);

app.use(function(err, req, res, next){
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json({limit: '50mb'}));
    console.log(err);
});

app.post('/savedata', function(req,res){
    console.log('Here');
    console.log(req.body);
    var currentTime = Date.now();
    /*fs.writeFile('./json/'+currentTime+'.json', JSON.stringify(req.body), function (err) {
        if (err) return console.log(err);
        else res.send();
    }); */
});


http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

On the above /savedata method req is coming blank. Where is the mistake in my code.

2
  • Did you check on firebug if call is being made to saveData and what response is coming ? You need to identify first whether the issue is at the client or server. Commented Sep 21, 2015 at 6:52
  • Yes i checked it. On $scope.saveJson method data is posted correctly. But when i passed the data to multipartForm via multipartForm.post(uploadUrl, $scope.formData); then multipartForm's post method not posting data. Problem is multipartForm service's post method i think. @brute_force Commented Sep 21, 2015 at 6:57

1 Answer 1

1

http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

  <div ng-controller = "myCtrl">
     <input type = "file" file-model = "myFile"/>
     <button ng-click = "uploadFile()">upload me</button>
  </div>

  <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;

           console.log('file is ' );
           console.dir(file);

           var uploadUrl = "/fileUpload";
           fileUpload.uploadFileToUrl(file, uploadUrl);
        };
     }]);

  </script>

simply copy paste and change your api path in url required for angular service calling from controller then it will work :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.