Reputation: 155
I need to create the uploaded structure of data as : { "authentication_token":"some_token", "user": { "fname": "fname", "lname": "lname", "avatar": "image-file" "location": "location" } }
The "avatar" is actually an Image File (profile image of the user).
I've tried to create the structure using Apache's MultipartEntity class, adding FileBody & StringBody objects. For key-value pairing, I've used NameValuePair. But I'm not able to add the User object separately. I don't know how to.
I looked for answers in these links : MultiPartEntity along with plain text in android Android Multipart Upload How to send multiple images to server using MultipartEntity from android http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/
Upvotes: 0
Views: 2499
Reputation: 155
After so much research, I've finally found a working solution, don't know whether it is the best one. I had to use Apache's MultipartEntity and its helper classes.
Here's the code :
ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
BasicNameValuePair bn;
bn = new BasicNameValuePair("authentication_token", app.getSystemValue("authentication_token"));
nameValuePairs.add(bn);
bn = new BasicNameValuePair("fname", user.getFname());
nameValuePairs.add(bn);
bn = new BasicNameValuePair("lname", user.getLname());
nameValuePairs.add(bn);
bn = new BasicNameValuePair("location", user.getLocation());
nameValuePairs.add(bn);
bn = new BasicNameValuePair("avatar", user.getAvatar());
nameValuePairs.add(bn);
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter("Connection", "Keep-Alive");
client.getParams().setParameter("Content-Type", "multipart/form-data;");
client.getParams().setParameter("http.socket.timeout", Integer.valueOf(TIMEOUT_WAIT_TO_CONNECT));
client.getParams().setParameter("http.connection.timeout", Integer.valueOf(TIMEOUT_WAIT_FOR_DATA));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
int i=0;
for (BasicNameValuePair nameValuePair : nameValuePairs) {
if (nameValuePair.getName().equalsIgnoreCase("avatar")) {
File imgFile = new File(nameValuePair.getValue());
FileBody fileBody = new FileBody(imgFile, "profile.jpeg", "image/jpeg", "UTF-8");
multipartEntity.addPart("user[avatar]", fileBody);
}
else {
if (nameValuePair.getValue()!=null) {
if (i==0) {
multipartEntity.addPart(nameValuePair.getName(), new StringBody(nameValuePair.getValue()));
}
else {
multipartEntity.addPart("user[" + nameValuePair.getName() + "]", new StringBody(nameValuePair.getValue()));
}
}
}
i++;
}
HttpPost post = new HttpPost(serviceUri);
post.setEntity(multipartEntity);
HttpResponse response = client.execute(post);
I hope it helps someone in need.
Upvotes: 1