Sending nested JSON with image

3.7k views Asked by At

I have been trying to research a way to be able to send nested JSON requests via Ajax back to the server. From my understanding formdata that we mostly use for sending images or files to the server wont work in this scenario, since it seems like FormData does not handle nested objects.

This is the kind of payload I need to send. Any suggestions?

payload = {
  'login':{
    'key':'some_key'
  },
  'user':{
    'doc':{
      'dp':<here will be the image file>,
      'date':"some date",
      'extra':"extra info"
    },
    'fingerprint':'some_fingerprint'
  }
} 
1

There are 1 answers

1
nixkuroi On

I've never been able to send image data over Json, but I have been able to attach json data to a formData object and pull it apart on the server from the request object.

payload = {
  'login':{
    'key':'some_key'
  },
  'user':{
    'doc':{
      'dp':"filename you can reassociate on the other side",
      'date':"some date",
      'extra':"extra info"
    },
    'fingerprint':'some_fingerprint'
  }
} 

var imageData = new FormData();

jQuery.each($('#fileInput')[0].files, function (i, file)
{
    var fname = i + "_";
    imageData.append(fname, file);
});

imageData.append("payload", JSON.stringify(payload));

$.ajax({
            url: 'api/imageupload/',
            type: 'POST',
            // Form data
            data: imageData,
            //Options to tell JQuery not to process data or worry about content-type
            cache: false,
            contentType: false,
            processData: false,
            async: false
        }).done(function (data)
        {
            alert("woo!");

        });

In your server side code, you just pull out the "payload" property and parse it there, and then loop through your formData and pull out the images.