节点上传文件$ http.post来自angularjs有未定义的req.body

时间:2016-06-16 17:39:30

标签: node.js angularjs-http

我使用我的angularjs应用程序构建文件上传功能,该应用程序将文件上传到我的节点api,该节点将ftp到cdn服务器。现在我只是得到了hte文件。我尝试使用multer,但我不确定如何防止保存重定向到ftp。

无论如何,这是我的代码而不是multer

 <input type="file" multiple  file-model="fileRepo"/>


myApp.directive('fileModel', ['$parse', function ($parse) {
        return {
           restrict: 'A',
           link: function(scope, element, attrs) {
              element.bind('change', function(){
                $parse(attrs.fileModel).assign(scope,element[0].files)
                scope.$apply();
              });
           }
        };
     }]);

///控制器///

$scope.saveFile = function(){
        var fd=new FormData();
        angular.forEach($scope.fileRepo,function(file){
            fd.append('file',file);
        });

        $scope.newFile.files = fd;

        FileService.uploadFile($scope.newFile)
.....

/// fileservice ///

uploadFile: function(file){
           var deferred = $q.defer();

var uploadUrl = '/api/file/ftp/new';
                var requestFileUpload = {
                        method: 'POST',
                        url: uploadUrl,
                        data: file.files
                    }
                var requestFileUploadConfig = {
                    transformRequest: angular.identity,
                    headers: { 'Content-Type': undefined }
                }
                $http.post(uploadUrl, file.files, requestFileUploadConfig)
                    .then(function(){
                     })

///节点部分///

router.post('/ftp/new',  function(req, res) {
        console.log('file is ' + JSON.stringify(req.body));
    });

1 个答案:

答案 0 :(得分:1)

您必须使用HTML解析器,只需阅读请求就无法捕获该文件。

我建议使用busboyconnect-busboy然后您将能够阅读您的文件,这是一个小例子:

req.pipe(req.busboy);
req.busboy.on('file',function(fieldname, file, filename, encoding, contentType){
    // get data 
    file.on('data',function(data){

    }).on('end', function(){

    });
});


req.busboy.on('field',function(fieldname, val){
    req.body[fieldname] = val;
});

req.busboy.on('finish', function() {
    // save file here
});