Gitesh Purbia
Gitesh Purbia

Reputation: 1104

Data not posting in multipart form data in angular and node js(File uploading with angular and node js)

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.

Upvotes: 0

Views: 1551

Answers (1)

Chandra Kant Paliwal
Chandra Kant Paliwal

Reputation: 121

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 :)

Upvotes: 1

Related Questions