包含文字和图片的JSON

时间:2015-09-18 14:19:19

标签: android ios json post

我需要将有关用户的信息上传到服务器,包括头像。到目前为止它工作正常,我使用FTP传输上传图像,意味着JSON只有用户的文本信息。

但我希望将两者结合在一起。像这样:

{
    name: 'Jason Manson',
    age: 45,
    gender: 0,
    avatar: [IMG element]
}

这可能吗?如果是的话,如何在Xcode,Android和php中使用它?任何可用的样本。

这适用于两者,从应用程序发送到服务器并从服务器返回到应用程序。

1 个答案:

答案 0 :(得分:0)

您必须使用使用Json上传图像的多部分系统,您可以使用以下方法将带有JSON(文本)的单个或多个图像上传到服务器......! mImagePath是图像路径的arraylist

// Method for sending files using multiparting......
public static String sendJsonWithFile(Activity mActivity, ArrayList<String> mImagePaths, String jsonString, String URL)
{
    Log.e("json", jsonString);
    String res = "";
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);
        String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
        boundary = "--" + boundary;
        httppost.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    StringBody stringBody = new StringBody(jsonString);

    reqEntity.addPart("formstring", stringBody);

    for (int i = 0; i < mImagePaths.size(); i++)
    {
        String imagePath = mImagePaths.get(i);
        if (mImagePaths != null && mImagePaths.size() > 0)
        {

            byte[] filebytes = FileUtils.readFileToByteArray(new File(imagePath));

            ByteArrayBody filebodyImage = new ByteArrayBody(filebytes, "image");
            Log.e("file path=", filebodyImage.toString());

            reqEntity.addPart("image", filebodyImage);

        }

    }

    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    if (resEntity != null)
    {
        res = EntityUtils.toString(resEntity);
        System.out.println(res);
    }

    if (resEntity != null)
    {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}
catch (UnsupportedEncodingException e)
{
    res = "UnsupportedEncodingException";
    e.printStackTrace();
}
catch (ClientProtocolException e)
{
    res = "ClientProtocolException";
    e.printStackTrace();
}
catch (FileNotFoundException e)
{
    res = "FileNotFoundException";
    e.printStackTrace();
}
catch (IOException e)
{
    res = "IOException";
    e.printStackTrace();
}
catch (Exception e)
{
    res = "Exception";
    e.printStackTrace();
}
return res;
}