2015-09-18 78 views
-1

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

但我想结合在一个JSON。类似这样的:

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

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

这是为了从应用程序发送到服务器,并从服务器返回到应用程序。

回答

0

您应该使用JSON上传图片的多部分系统,您可以使用下面的方法将带有JSON(文本)的单个或多个图片上传到服务器...! mImagePath是图像路径的阵列列表

// 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; 
} 
相关问题