数据未在角度和节点js中的多部分表单数据中发布(使用angular和node js上传文件)

时间:2015-09-21 06:39:41

标签: angularjs node.js file-upload

我更喜欢使用Angular js和节点js。我正在通过angular和node js进行文件上传过程。我已经通过观看一些教程来创建指令和服务。但是在服务中,表单数据不会在NodeJs服务器上发布。以下是按文件的代码文件: -

这是我的指示: -

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

这是我的angularjs代码,我定义了所有方法: -

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

    }]);

当我通过此服务将数据发布到节点js服务器时,我的console.log req.body和rex.files变为空白。我的代码中的问题在哪里。这是我的Node js服务器文件(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'));
});

在上面/ savedata方法上,req变为空白。我的代码中的错误在哪里。

1 个答案:

答案 0 :(得分: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>

只需复制粘贴并在控制器调用角度服务所需的URL中更改api路径然后它就可以工作:)