gdubs gdubs - 5 months ago 79
Node.js Question

node uploading file $http.post from angularjs has undefined req.body

I'm building a file upload functionality with my angularjs app that would upload a file to my node api that will ftp to a cdn server. Right now I'm stuck with just getting hte file. I tried using multer but I'm not sure how to prevent the save to redirect to an ftp.

Anyway, this is my code withoout 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();
});
}
};
}]);


///controller///

$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(){
})


/// node part ///

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

Answer

You'll have to use an HTML parser you are not going to be able to catch the file just by reading the request.

I'd recommend use busboy and connect-busboy then you are going to be able to read your file, this a small example:

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