本文介绍了如何上传到Android中使用HttpPost服务器的形象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code使用HttpPost一些数据发送到PHP服务器JSON格式。我如何与数据一起上传图片?

Here is my code to send some DATA to php server in Json format using HttpPost. How can i upload a image along with the DATA ?

HttpPost httppost = new HttpPost(urlToSendCheckListReport);  
JSONObject json = new JSONObject();
        // prepare JSON data:
        json.put("tag_id", tagID);
        json.put("building_id", buildingID);
        json.put("timestamp", new SimpleDateFormat("dd-MM-yyyy, HH:mm:ss").format(Calendar.getInstance().getTime())); 

        JSONArray postjson=new JSONArray();
        postjson.put(json);  

        // Post the data:
        httppost.setHeader("json", json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);  

   HttpResponse response = new DefaultHttpClient().execute(httppost);

    if(response != null)
    { 
     .....Read the response
    }

在此先感谢

推荐答案

试试这个:

HttpPost httppost = new HttpPost(urlToSendCheckListReport);  
JSONObject json = new JSONObject();
    // prepare JSON data:
    json.put("tag_id", tagID);
    json.put("building_id", buildingID);
    json.put("timestamp", new SimpleDateFormat("dd-MM-yyyy, HH:mm:ss").format(Calendar.getInstance().getTime())); 

    JSONArray postjson=new JSONArray();
    postjson.put(json);  

    // IMAGE
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
    byte[] data = bos.toByteArray();
    String mediaString = Base64.encodeBytes(data);
    // /IMAGE

    // Post the data:
    httppost.setHeader("json", json.toString());
    httppost.getParams()
    .setParameter("jsonpost",postjson)
    .setParameter("image", new StringBody(mediaString));  //ADD IMAGE PARAMETER

   HttpResponse response = new DefaultHttpClient().execute(httppost);

    if(response != null)
    { 
     .....Read the response
    }

这篇关于如何上传到Android中使用HttpPost服务器的形象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 19:54