3

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'
  }
} 
Jonathan
  • 2,728
  • 10
  • 43
  • 73
  • You send this on a form submission or Ajax? – Varun Jun 19 '15 at 06:08
  • @Varun Ajax is the idea – Jonathan Jun 19 '15 at 06:09
  • 1
    JSON doesn't have an image format. It's not part of the spec. It does however have strings. Convert the image file to a base64 string, send it via JSON, and convert it back on the backend. That's just one approach. – Gabriel L. Jun 19 '15 at 06:12
  • As @GabrielLebec mentioned you cant send a image directly in JSON.Either encode it in base64 or use FormData. – Varun Jun 19 '15 at 06:13
  • @GabrielLebec thanks, I might try that, so I will have to convert Blob to base64, something like this? http://stackoverflow.com/questions/18650168/convert-blob-to-base64 – Jonathan Jun 19 '15 at 06:25

1 Answers1

3

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.

nixkuroi
  • 2,259
  • 1
  • 19
  • 25