[英]How to upload a image to server using HttpPost in android?
Here is my code to send some DATA to php server in Json format using HttpPost. 这是我的代码,使用HttpPost以Json格式将一些数据发送到php服务器。 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
}
Thanks in advance 提前致谢
Try with this: 试试这个:
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
}
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);
StringEntity entity = null;
try {
entity = new StringEntity(entityString);
entity.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httppost.setEntity(entity);
// 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.