发送带有图像的嵌套JSON [英] Sending nested JSON with image

查看:55
本文介绍了发送带有图像的嵌套JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试研究一种方法,该方法能够通过Ajax将嵌套的JSON请求发送回服务器.根据我的理解,在这种情况下,我们最常用于将图像或文件发送到服务器的formdata将无法正常工作,因为FormData似乎无法处理嵌套对象.

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'
  }
} 

推荐答案

我从未能够通过Json发送图像数据,但是我已经能够将json数据附加到formData对象并将其在服务器上拆开来自请求对象.

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!");

        });

在服务器端代码中,您只需拉出"payload"属性并在其中进行解析,然后遍历formData并拉出图像.

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.

这篇关于发送带有图像的嵌套JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆