Skip to content

Instantly share code, notes, and snippets.

@fazlurr
Last active July 19, 2022 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fazlurr/eba500d414edca6b243d to your computer and use it in GitHub Desktop.
Save fazlurr/eba500d414edca6b243d to your computer and use it in GitHub Desktop.
Android Image Upload Using MultipartEntity Builder
private String updateProfile(Map map) {
File image = (File) map.get(KEY_IMAGE);
File background = (File) map.get(KEY_BACKGROUND);
FCUser user = (FCUser) map.get(KEY_USER);
String userJsonString = user.toJSONUpdate().toString();
// TODO : Change HTTPClient to HttpUrlConnection or Android Async HTTP and Upload Image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(FlipCardClient.API_PROFILE);
HttpResponse httpResponse;
HttpEntity httpEntity;
String response = "";
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// Image
if (image != null) {
FileBody fileBodyImage = new FileBody(image);
builder.addPart(KEY_IMAGE, fileBodyImage);
}
// Background
if (background != null) {
FileBody fileBodyBackground = new FileBody(background);
builder.addPart(KEY_BACKGROUND, fileBodyBackground);
}
// User ID
String userId = String.valueOf(user.getId());
builder.addTextBody(KEY_USER_ID, userId, ContentType.TEXT_PLAIN);
// User Profile JSON String
builder.addTextBody(KEY_PROFILE, userJsonString, ContentType.TEXT_PLAIN);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.v(TAG, "Something wrong with I/O operation");
e.printStackTrace();
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment