I am trying to upload an image to a server along with some JSON data that is collected from a form.
The server has authentication.
METHOD: post
HEAD
I know this post is a couple of years old, but I'd like to share my solution using MultiPartEntity from here available as part of the HttpClient download. I used version 4.2.5.
I originally used a process similar to above, which worked well until I started getting memory errors when I started supporting uploading of videos. I researched a lot of posts here and got a lot of good ideas. I used the Java Decompiler available here to look at the code in the Jar file to figure out how to put things together.
//filepath is passed in like /mnt/sdcard/DCIM/100MEDIA/VIDEO0223.mp4
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
String json = "{your_json_goes_here}";
File media = new File(filePath);
URI uri = your_uri_goes_here;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
StringBody jsonBody = new StringBody(json, "application/json", null);
FormBodyPart jsonBodyPart = new FormBodyPart("json", jsonBody);
String mimeType;
if (requestCode == Constants.ACTION_TAKE_VIDEO) {
mimeType = "video/" + extension;
} else {
// default to picture
mimeType = "image/" + extension;
}
FileBody fileBody = new FileBody(media, mimeType, "ISO-8859-1");
FormBodyPart fileBodyPart = new FormBodyPart(fileName, fileBody);
MultipartEntity mpEntity = new MultipartEntity(null, "xxBOUNDARYxx", null);
mpEntity.addPart(jsonBodyPart);
mpEntity.addPart(fileBodyPart);
post.addHeader("Content-Type", "multipart/mixed;boundary=xxBOUNDARYxx");
post.setEntity(mpEntity);
HttpResponse response = httpClient.execute(post);
InputStream data = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(data));
String responseLine;
StringBuilder responseBuilder = new StringBuilder();
while ((responseLine = bufferedReader.readLine()) != null) {
responseBuilder.append(responseLine);
}
System.out.println("Response: " + responseBuilder.toString());
Try this Code it's easy
public String postAsync(String url, String action, JSONObject jsonObject, String fileUri) throws JSONException {
String result = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.STRICT);
File file = new File(fileUri);
entityBuilder.addPart("file", new FileBody(file));
entityBuilder.addTextBody(DMConstant.ACTION_JSON, action);
entityBuilder.addTextBody(DMConstant.DATA_JSON, jsonObject.toString(), ContentType.create("application/json", Consts.UTF_8));
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
result = dmUtils.convertStreamToString(inputStream);
} else {
Log.i("Input Stream is Null", "Input Stream is Null");
}
} catch (UnsupportedEncodingException e) {
Log.e("Unsupported Encoding", e.getMessage());
} catch (ClientProtocolException e) {
Log.e("Client Protocol", e.getMessage());
} catch (IOException e) {
Log.e("IOException", e.getMessage());
}
Log.i("JSON Object as Response", result);
return result;
}
........
JSONObject urlObject = new JSONObject();
urlObject.put("userName", "user name");
urlObject.put("email_id", "äbc@gmail.com");
urlObject.put("user_pass", "123456");
postAsync(URL, "php function name", urlObject, imageFile);
public static boolean uploadImage(final byte[] imageData, String filename ,String message) throws Exception{
String responseString = null;
PostMethod method;
String auth_token = Preference.getAuthToken(mContext);
method = new PostMethod("http://10.0.2.20/"+ "upload_image/" +Config.getApiVersion()
+ "/" +auth_token);
org.apache.commons.httpclient.HttpClient client = new
org.apache.commons.httpclient.HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(
100000);
FilePart photo = new FilePart("icon",
new ByteArrayPartSource( filename, imageData));
photo.setContentType("image/png");
photo.setCharSet(null);
String s = new String(imageData);
Part[] parts = {
new StringPart("message_text", message),
new StringPart("template_id","1"),
photo
};
method.setRequestEntity(new
MultipartRequestEntity(parts, method.getParams()));
client.executeMethod(method);
responseString = method.getResponseBodyAsString();
method.releaseConnection();
Log.e("httpPost", "Response status: " + responseString);
if (responseString.equals("SUCCESS")) {
return true;
} else {
return false;
}
}
You can also see an Example on my blog Here
Do not reinvent the wheel! The Apache HttpClient have implemented your requires.
Android JSON HttpClient to send data to PHP server with HttpResponse
Goog luck!
The last line should be --xxxxxxxx--
, and not --xxxxxxxx
.
This is an example to upload image and JSONArray using MultipartEntity-- lib:org.apache.http.entity.mime
List <Entity> students = getStudentList();
MultipartEntity studentList = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i=0; i<students.size();i++){
try {
studentList.addPart("studentList[][name]", new StringBody(String.valueOf(students.get(i).getName())));
studentList.addPart("studentList[][addmission_no]", new StringBody(String.valueOf(students.get(i).getAddmissionNo)));
studentList.addPart("studentList[][gender]", new StringBody(String.valueOf(students.get(i).getGender)));
File photoImg = new File(students.get(i).getImagePath());
studentList.addPart("studentList[][photo]",new FileBody(photoImg,"image/jpeg"));
}catch(Exception e){
e.getMessage();
}
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.addHeader("X-Auth-Token", mUserToken);
post.setEntity(studentList);
org.apache.http.HttpResponse response = null;
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = response.getEntity();
JSONObject myObject;
try {
String result = EntityUtils.toString(httpEntity);
// do your work
} catch (IOException e) {
e.printStackTrace();
}