Android Image Upload to Server

Oyewale Ademola
3 min readJan 10, 2016

Updated link to a recent version with Kotlin: https://saopayne.medium.com/android-image-upload-to-server-with-kotlin-2-96605f14845a

Uploading images is something that has been integrated into our lives that we really don’t bother our brains with the choice of uploading or not. Instagram built its billion-dollar company right around this singular feature but then a lot of other things were involved.

Other examples of where we perform this action include Facebook, Twitter, Whatsapp, BBM, and some mobile applications that require changing of Profile and cover pictures.

As developers, this poses an interesting technical challenge and we are glad about this challenge.

This write-up is focused on implementing this on Android which sends the image and is stored on a server somewhere implemented by tools of choice.

Uploading images can be looked on the top-level as a series of steps listed below ;

1. Select the Image to upload via an Intent

2. Act on the result if successful

3. Upload to server

4. If the upload is successful/not, pass the message accordingly.

Let me save the details a little and go straight to the code.

  1. Handling the User’s click on a button to change/upload an image.
private int PICK_PROFILE_IMAGE_REQUEST = 1;changeProfileImage.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){showFileChooser(PICK_PROFILE_IMAGE_REQUEST);}});

2. The Chooser Intent to select Image via the gallery

private void showFileChooser(int number){Intent intent= new Intent();intent.setType("image/*");intent.setAction(Intent.ACTION_GET_CONTENT);switch(number){case 1:
startActivityForResult(Intent.createChooser(intent,"Select
Picture"), PICK_PROFILE_IMAGE_REQUEST)
break;
}
}

3. Handling the result of the Intent when the Image has been selected by the User.

@Overridepublic void onActivityResult(intrequestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode,data);if(requestCode == PICK_PROFILE_IMAGE_REQUEST && resultCode == 
getActivity().RESULT_OK && data != null && data.getData() != null){
Uri filePath = data.getData();String fileName = getFileNameByUri(getActivity(),filePath);try {bitmap = MediaStore.Images.Media .getBitmap(getActivity().getContentResolver(), filePath);uploadProfileImage(fileName);profilePicture.setImageBitmap(bitmap);} catch(IOException e){e.printStackTrace();}}

4. Uploading to the server in the background( using AsyncTask so as not to block the UI)

public byte[] getBytesImage(Bitmapbmp){ByteArrayOutputStream baos = new ByteArrayOutputStream();bmp.compress(Bitmap.CompressFormat.PNG,100, baos);byte[] imageBytes = baos.toByteArray();return imageBytes;}public static String getFileNameByUri(Context context, Uri uri){String fileName="unknown";//default fileName
Uri filePathUri = uri;
if (uri.getScheme().toString().compareTo("content")==0)
Cursor cursor = context.getContentResolver().query(uri,null,null,
null, null);
if (cursor.moveToFirst()){
int column_index =
cursor.getColumnIndex(MediaStore.Images.Media.DATA);
filePathUri = Uri.parse(cursor.getString(column_index));
if(filePathUri == null){
fileName = "xxx.png";//load a default Image from server
}else{
fileName = filePathUri.getLastPathSegment().toString();
}
}
}else
if (uri.getScheme().compareTo("file")==0){
fileName = filePathUri.getLastPathSegment().toString();
}else{
fileName = fileName+"_"+filePathUri.getLastPathSegment();
}
return fileName;
}
public void uploadProfileImage(final String fileName){
byte[] imageBytes = getBytesImage(bitmap);
httpclient = new DefaultHttpClient();
httpPost = new HttpPost(“URL to upload image to...“);
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data;
boundary="+boundary);
ByteArrayBody bab = new ByteArrayBody(imageBytes,fileName);
StringBody userId = new StringBody(mPrefs.getUser().getId(),
ContentType.TEXT_PLAIN);
StringBody type = new StringBody("baby",ContentType.TEXT_PLAIN);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.setBoundary(boundary)
.addPart("imageUpload",bab)
.addPart("userid",userId)
.addPart("type",type)
.build();
httpPost.setEntity(entity);
class UploadImage extends AsyncTask<Void,Void,String> { ProgressDialog loading; @Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(getActivity(),"Please
wait...","uploading picture",false,false);
} @Override
protected void onPostExecute(String s){
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
}

@Override
protected String doInBackground(Void...param){
String res = "";
HttpResponse response;
try{
response = httpclient.execute(httpPost);
res = response.getStatusLine().toString();
User user = mPrefs.getUser();
user.setProfileImageUrl(PICTURE_URL+fileName);
mPrefs.saveUser(user);
}catch(IOException e){
e.printStackTrace();
}
return "Profile image upload successful"
}
}
UploadImage u = new UploadImage();
u.execute();
}

It’s as simple as it looks, looking forward to getting your reviews and comments.

Good luck.

--

--