Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I receive a json object and files in a multiparty form?

I'm trying to build an angularJS page that posts a username, password and a profile pic. I'm using a custom fileUpload directive and then then sending both fields and files as a multipart form request.

On the server side, I am able to get the files all right using multiparty but the fields data appears as {[object object]} and I can't get to it. Tried JSON.stringify but that doesn't work either.

Here's my code:

View

<form ng-submit="submitForm(user)">
            <input type="text" ng-model="user.username" placeholder="user name">
            <input type="text" ng-model="user.age" placeholder="age">
            <input type="password" ng-model="user.password"      placeholder="password">
            <input type="file" file-upload multiple/>
            <input type="submit" class="btn btn-danger">Send</button>
        </form>

angular controller code:

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

app.directive('fileUpload', function () {
    return {
        scope: true,        
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var files = event.target.files;

                for (var i = 0;i<files.length;i++) {
                    scope.$emit("fileSelected", { file: files[i] });
                }                                       
            });
        }
    };
});



app.controller('photoController', function($scope, $http){
    $scope.files = [];

    //listen for the file selected event
    $scope.$on("fileSelected", function (event, args) {
        $scope.$apply(function () {            
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
            console.log('$scope.files has', $scope.files)
        });
    });


    $scope.submitForm = function(user) {

       $http({
                method: 'POST',
                url: 'http://localhost:3050/user',
                headers: { 'Content-Type': undefined },
                transformRequest: function(data) {
                var fd = new FormData();
                fd.append('user', user);
                for (var i = 0; i < data.files.length; i++) {
                fd.append('file' + i, data.files[i]);
                }
                return fd;
                },
                data: { model: $scope.model, files: $scope.files }
                }).
        success(function (data, status, headers, config) {

        }).
        error(function (data, status, headers, config) {
            alert("failed!");
        });
    };
});

Backend node.js api -

app.post('/user', function (req, res) {
var count=0
var form = new multiparty.Form();
var uploadDir = __dirname + '/../uploads/fullsize/'
var size = '';
var fileName = '';
var data = {}
var fields = []
var fieldCount = 0

form.on('field', function(name, val){
  fields.push('{"'+name+'":'+val+'}')
  console.log('fields array now has:', fields[fieldCount])
  var fieldsStringified = JSON.stringify(fields[fieldCount])
  console.log('fieldsStringified:',fieldsStringified)
  fieldCount++
      });


form.on('file', function(name,file){
    count++
    var tmp_path = file.path
  var target_path = uploadDir + 'profilePic' + count+'.jpg';
    mv(tmp_path, target_path, function(err){
      if (err) {
          console.error(err.stack)
      }
        console.log('file '+target_path+ 'saved' )


      })


    }) //--- end app.post()

What I would ideally like to see happen is receive the user{} object as JSON so I can create a record in mongo, get the record _id and use that to name my files. Note that I can receive both files and fields fine. I just need help converting the incoming fields to JSON.

Really appreciate any help you can provide.

like image 211
Kris B Avatar asked Dec 12 '25 21:12

Kris B


1 Answers

Problem solved. Got the data as 'fields' then converted them to json object using json.parse()

//Push field onto an array
form.on('field', function(name, val){
          fields.push('"' +name+ '"'+ ':'+'"'+val+'"')
         });
//finally convert array to json obj
form.on('close', function(){
  var str = '{'+fields.toString() +'}'
  var user = JSON.parse(str)
like image 115
Kris B Avatar answered Dec 15 '25 12:12

Kris B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!